【问题标题】:Files uploaded using http PUT are not of exact size on the server使用 http PUT 上传的文件在服务器上的大小不准确
【发布时间】:2018-03-25 12:07:41
【问题描述】:

我正在尝试使用预签名 URL 将不同 MIME 类型的文件上传到 AWS S3。我可以在 S3 上看到文档,但内容不合适。它是 0 字节或小于我正在尝试的每个文件的预期大小。

这是代码,请告诉我缺少什么:

public static void main(String[] args) {

    URLConnection urlconnection = null;

    try {
        File file = new File(File_Path);

        if (isEncoded == "false") {
            URL obj = new URL(Upload_Url);
            urlconnection = obj.openConnection();
        } else {
            try {
                URI uri = new URI(Upload_Url);
                URL url = uri.toURL();
                urlconnection = url.openConnection();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
            ((HttpURLConnection) urlconnection).setRequestProperty("Content-Type", Content_Type);
            ((HttpURLConnection) urlconnection).connect();
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) > 0) {
            bos.write(i);
        }
        bis.close();
        bos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

【问题讨论】:

  • 是内容还是大小?有什么例外吗?
  • 返回了什么 HTTP 状态码?
  • 文件大小不合适。因此,当我下载文件时,它已损坏。
  • 上传成功,收到200
  • 你怎么知道这个代码的 HTTP 状态代码是什么?

标签: java http file-upload put


【解决方案1】:

您的流尾检测似乎是错误的,因此当您看到空字节时会截断。

【讨论】:

  • 从上传到服务器的文本文件中,我看到内容在遇到以下字符时停止:ã™VJŒ/Õ+)™T≤RV“Q*.I,IU ≤RrvT“QJŒ,I8˙¯+8˙ѯ+'ˇˇ a C¯ôk0 如何确保在实际到达文件末尾时检测到流尾?
  • 我试过了:while ((i = bis.read()) != -1) { bos.write(i);这解决了文本文件,我可以看到上传到服务器的文件的全部内容。但图像仍为 0 字节。有什么帮助吗?
  • @Jayashree 我建议你重新测试一下。这个答案是正确的。
  • 是的,我也可以上传图片。我试图从中读取的基本映像存在问题。感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多