java 如何使用 URLConnection 上传二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13480160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload binary file using URLConnection
提问by perissf
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:
为了将二进制文件上传到 URL,我被建议使用本指南。但是,该文件不在目录中,而是存储在 MySql db 中的 BLOB 字段中。BLOB 字段被映射为byte[]
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
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.
主机正确接收所有标头。它也接收上传的文件,但不幸的是抱怨文件不可读,并断言接收到的文件的大小比我的代码输出的大小大37个字节。
My knowledge of streams, connections and byte[] is too limited for grasping the way to fix this. Any hints appreciated.
我对流、连接和 byte[] 的知识太有限,无法掌握解决这个问题的方法。任何提示表示赞赏。
EDIT
编辑
As suggested by the commenter, I have tried also to write the byte[] directly, without using the ByteArrayInputStream:
正如评论者所建议的那样,我也尝试过直接编写 byte[],而不使用 ByteArrayInputStream:
output.write(myEntity.getBinaryFile());
Unfortunately the host gives exactly the same answer as the other way.
不幸的是,主持人给出了与其他方式完全相同的答案。
采纳答案by perissf
My code was correct.
我的代码是正确的。
The host was giving an error because it didn't expect the Content-Transfer-Encoding
header. After removing it, everything went fine.
主机给出错误,因为它不希望Content-Transfer-Encoding
标头。取出后,一切正常。