【问题标题】:How to upload binary file using URLConnection如何使用 URLConnection 上传二进制文件
【发布时间】:2012-11-08 22:20:24
【问题描述】:

为了将二进制文件上传到 URL,建议我使用this guide。但是,该文件不在目录中,而是存储在 MySql db 的 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个字节。

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


编辑

根据评论者的建议,我也尝试过直接写入 byte[],而不使用 ByteArrayInputStream:

output.write(myEntity.getBinaryFile());

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

【问题讨论】:

  • 为什么要通过 BAIS 流式传输文件?为什么不直接从字节数组本身写入?
  • @JimGarrison 感谢您的提示,我已经更新了我的问题
  • 如果不使用file.available() 而使用byte[] temp = myEntity.getBinaryFile(); 并使用temp.length 会发生什么?我怀疑file.available() 已关闭。
  • 在这种情况下,file.available() 是准确的,给出了确切的字节数。我刚刚解决了这个问题:使用主机接收到的文件中的字节数过多的提示,我删除了 Content-Transfer-Encoding 标头和一个结束行,现在可以了。无论如何感谢您的帮助!

标签: java upload stream httpurlconnection


【解决方案1】:

我的代码是正确的。

主机出现错误,因为它没有预料到 Content-Transfer-Encoding 标头。删除后一切正常。

【讨论】:

    猜你喜欢
    • 2016-03-09
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2011-02-24
    • 2011-09-17
    • 2021-12-18
    相关资源
    最近更新 更多