2015-10-19 85 views
3

因此,我從數據庫(各種mimetypes)抓取了一組blob,並試圖將它們壓縮成由用戶通過http響應下載。我可以讓下載發生,但是當我嘗試打開下載的zip文件時,它會顯示「存檔文件格式未知或已損壞。」我嘗試了下面的代碼,使用application/zip,application/octet-stream和application/x-zip-compressed,但我開始認爲問題在於我如何添加文件。我也在使用Java 7和Grails 2.2.4。通過HttpResponse下載Zip文件Java

任何幫助,這將不勝感激。謝謝!

final ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip")); 


     for (Long id : ids){ 

      Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id); 


      if (stream) { 

       String fileName = stream[0] 
       String mimeType = (String) stream[1]; 
       InputStream inputStream = stream[2] 
       byte[] byteStream = inputStream.getBytes(); 

       ZipEntry zipEntry = new ZipEntry(fileName) 
       out.putNextEntry(zipEntry); 
       out.write(byteStream, 0, byteStream.length); 
       out.closeEntry(); 
      } 
     } 

     out.close(); 
     response.setHeader("Content-Disposition", "attachment; filename=\"" + "test.zip" + "\""); 
     response.setHeader("Content-Type", "application/zip"); 
     response.outputStream << out; 
     response.outputstream.flush(); 
+0

這似乎或多或少好,至少你寫文件的方式應該工作。你有沒有試過運行這段代碼,讓它將文件保存到磁盤,看看你是否可以打開它,然後通過電線發送。 –

+0

@ ShaunStone感謝您回覆Shaun。我直接將它下載到我的電腦上,我可以毫無問題地打開它。我想這意味着問題在於我將其推入響應的方式? – Brewster

回答

5

我在這裏找到了答案:Returning ZipOutputStream to browser

好吧,那又怎樣結束了工作對我來說是轉換ZipOutputStream到一個ByteArrayOutputStream並將其寫入爲一個byte []迴應:

 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     final ZipOutputStream out = new ZipOutputStream(baos); 

     Calendar cal = Calendar.getInstance(); 
     String date = new SimpleDateFormat("MMM-dd").format(cal.getTime()); 

     final String zipName = "COA_Images-" + date + ".zip"; 



     for (Long id : ids){ 

      Object[] stream = inlineSamplesDataProvider.getAttachmentStream(id); 


      if (stream) { 

       String fileName = stream[0] 
       String mimeType = (String) stream[1]; 
       InputStream inputStream = stream[2] 
       byte[] byteStream = inputStream.getBytes(); 

       ZipEntry zipEntry = new ZipEntry(fileName) 
       out.putNextEntry(zipEntry); 
       out.write(byteStream, 0, byteStream.length); 
       out.closeEntry(); 
      } 
     } 

     out.close(); 

     response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\""); 
     response.setHeader("Content-Type", "application/zip"); 
     response.getOutputStream().write(baos.toByteArray()); 
     response.flushBuffer(); 
     baos.close(); 

感謝大家幫助!

+0

您可以將自己的答案標記爲正確答案,以獲得徽章:) – manuna

+0

感謝您的回答,它爲我節省了很多頭痛! – JJT