2017-04-07 28 views
0

我正在使用以下代碼從s3存儲桶中的對象獲取內容。我能夠將數據複製到本地文件中,但文件需要「下載」並且必須顯示在瀏覽器的下載列表中。 我搜索了一下這個和凸輪知道這與response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); 我試圖補充一點,但不知何故無法讓它工作。我的理解是,源代碼必須是轉換爲流的服務器上的文件。但我以輸入流的形式得到s3內容。如何在瀏覽器中將其作爲文件下載? 下面是除了文件讀取部代碼到目前爲止,我已經試過java - 使用servlet下載輸入流

AmazonS3 s3 = new AmazonS3Client(new ProfileCredentialsProvider());  
S3Object fetchFile = s3.getObject(new GetObjectRequest(bucketname, fileloc)); 
     final BufferedInputStream i = new BufferedInputStream(fetchFile.getObjectContent()); 
     response.setContentType("application/json"); 
     response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");    
     ServletOutputStream sos = response.getOutputStream(); 
     int bytesread = i.read(); 
     while(bytesread!=-1) 
     { 
      sos.write(bytesread); 
      bytesread = i.read(); 
     } 
     if(i!= null)i.close(); 
     if(sos!= null)sos.close(); 

回答

0

一切都是正確的。

//Set the size of buffer to stream the data. 
    byte []buffer=new byte[1024*8]; 

代替

int byte=i.read(); 

現在讀取文件。

while((length = yourInputStream.read(buffer))!=-1) 
    {  yourOutputStream.write(buffer); 
       } 
    System.out.println("File is downloaded."); 

此外,的try/catch內puting你的整個代碼塊將幫助你知道你的問題的確切原因。

+0

嗨,謝謝!但這並沒有什麼區別,我也沒有得到任何異常 – lavy

+0

嗨,還有其他的見解嗎?我仍然堅持這一個:( – lavy