java如何使用URLConnection上传二进制文件
为了将二进制文件上载到URL,建议我使用this guide。但是,该文件不在目录中,而是存储在MySql数据库中的BLOB字段中。BLOB字段在JPA中映射为byte[]
属性:
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字节
我对流、连接和字节[]的知识太有限,无法掌握解决此问题的方法。任何提示,不胜感激
编辑
正如评论员所建议的,我还尝试直接写入字节[],而不使用ByteArrayInputStream:
output.write(myEntity.getBinaryFile());
不幸的是,主持人给出的答案与另一种方式完全相同
# 1 楼答案
我的代码是正确的
主机给出错误,因为它不需要
Content-Transfer-Encoding
头。拆下后,一切正常