使用http PUT上传的文件在服务器上的大小不正确

问题描述:

我正尝试使用预先设置的URL将不同MIME类型的文件上传到AWS S3。我能够在S3上看到文档,但内容不恰当。它要么是0字节,要么小于我尝试的每个文件的预期大小。使用http PUT上传的文件在服务器上的大小不正确

下面是代码,请让我知道什么是缺少:

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(); 
    } 
+0

它是否符合内容或尺寸?有什么异常? – Lokesh

+0

什么HTTP状态码被返回? – EJP

+0

文件大小不合适。因此,当我下载文件时,它已损坏。 – Jayashree

似乎结束流的检测是错误的,因此你当你看到一个空字节截断。

+0

从上传到服务器的文本文件中,我看到内容在遇到下面的字符时就停止了:'T * R V“Q * .I,IU≤RrvT”QJŒ ,I8˙¯+ 8Ñ+' a Côô0 如何确保在到达文件结尾时检测到流结束? – Jayashree

+0

我试过:while((i = bis.read())!= -1)bos.write(i); }这解决了文本文件,我能够看到文件上传到服务器上的全部内容。但图像仍然在0字节。任何帮助? – Jayashree

+0

@Jayashree我建议你重新测试一下。这个答案是正确的。 – EJP