如何使用URLConnection上传二进制文件


问题内容

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

byte[] binaryFile;

我以这种方式稍微修改了指南中的代码:

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

我没有使用分块流。使用的标头是:

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

主机正确接收了所有标头。它还接收上载的文件,但不幸的是,它抱怨该文件不可读,并且断言所接收文件的大小比我的代码输出的大小大37个字节。

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


编辑

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

output.write(myEntity.getBinaryFile());

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


问题答案:

我的代码是正确的。

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