如何使用 URLConnection 上传二进制文件 [英] How to upload binary file using URLConnection

查看:39
本文介绍了如何使用 URLConnection 上传二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了将二进制文件上传到 URL,我被建议使用本指南.但是,该文件不在目录中,而是存储在 MySql db 中的 BLOB 字段中.BLOB 字段在 JPA 中映射为 byte[] 属性:

In order to upload a binary file to an URL, I have been advised to use this guide. However, the file is not in a directory, but is stored in a BLOB field in MySql db. The BLOB field is mapped as a byte[] property in JPA:

byte[] binaryFile;

我稍微修改了从指南中获取的代码,如下所示:

I have slightly modified the code taken from the guide, in this way:

HttpURLConnection connection = (HttpURLConnection ) new URL(url).openConnection();
// set some connection properties
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true); 
// set some headers with writer
InputStream file = new ByteArrayInputStream(myEntity.getBinaryFile());
System.out.println("Size: " + file.available());
try {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = file.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    } 
    output.flush();
    writer.append(CRLF).flush();
    writer.append("--" + boundary + "--").append(CRLF).flush();
} 
// catch and close streams

我没有使用分块流式传输.使用的标题是:

I am not using chunked streaming. The headers used are:

username and password
Content-Disposition: form-data; name="file"; filename="myFileName"
Content-Type: application/octet-stream"
Content-Transfer-Encoding: binary

主机正确接收所有标头.它也接收上传的文件,但遗憾的是抱怨文件不可读,并断言接收到的文件的大小比我的代码输出的大小大37个字节.

All the headers are received correctly by the host. It also receives the uploaded file, but unfortunately complains that the file is not readable, and asserts that the size of the received file is 37 bytes larger than the size outputed by my code.

我对流、连接和 byte[] 的了解太有限,无法掌握解决此问题的方法.任何提示表示赞赏.

My knowledge of streams, connections and byte[] is too limited for grasping the way to fix this. Any hints appreciated.

编辑

正如评论者所建议的,我也尝试过直接编写 byte[],而不使用 ByteArrayInputStream:

As suggested by the commenter, I have tried also to write the byte[] directly, without using the ByteArrayInputStream:

output.write(myEntity.getBinaryFile());

不幸的是,主持人给出了与其他方式完全相同的答案.

Unfortunately the host gives exactly the same answer as the other way.

推荐答案

我的代码是正确的.

主机给出错误,因为它不希望 Content-Transfer-Encoding 标头.删除后一切正常.

The host was giving an error because it didn't expect the Content-Transfer-Encoding header. After removing it, everything went fine.

这篇关于如何使用 URLConnection 上传二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆