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

查看:118
本文介绍了如何使用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\"\r\nContent-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天全站免登陆