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

per*_*ssf 11 java upload stream httpurlconnection

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

byte[] binaryFile;
Run Code Online (Sandbox Code Playgroud)

我稍微修改了从指南中获取的代码,这样:

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
Run Code Online (Sandbox Code Playgroud)

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

username and password
Content-Disposition: form-data; name=\"file\"; filename=\"myFileName\"\r\nContent-Type: application/octet-stream"
Content-Transfer-Encoding: binary
Run Code Online (Sandbox Code Playgroud)

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

我对stream,connections和byte []的了解太有限了,无法掌握解决这个问题的方法.任何提示赞赏.


编辑

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

output.write(myEntity.getBinaryFile());
Run Code Online (Sandbox Code Playgroud)

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

per*_*ssf 6

我的代码是正确的.

主机发出错误,因为它没有预料到Content-Transfer-Encoding标头.删除后,一切都很顺利.