2014-04-14 151 views
1

我試圖用java創建和下載使用restful服務的zip文件。但它不適合我。請看以下代碼:使用Restful服務下載zip文件

 @GET 
    @Path("/exportZip") 
    @Produces("application/zip") 
    public Response download(@QueryParam("dim") final String dimId, 
      @QueryParam("client") final String clientId, 
      @QueryParam("type") final String type, 
      @Context UriInfo ui) { 
     System.out.println("Start"); 

     ResponseBuilder response = null ; 

     String filetype = ""; 

     if(type.equalsIgnoreCase("u")){ 
      filetype = "UnMapped"; 

     }else if(type.equalsIgnoreCase("m")){ 
      filetype = "Mapped"; 

     } 
     try { 

      byte[] workbook = null; 
      workbook = engineService.export(dim, client, type); 

      InputStream is = new ByteArrayInputStream(workbook); 

      FileOutputStream out = new FileOutputStream(filetype + "tmp.zip"); 

      int bufferSize = 1024; 
      byte[] buf = new byte[bufferSize]; 
      int n = is.read(buf); 
      while (n >= 0) { 
       out.write(buf, 0, n); 
       n = is.read(buf); 
      } 

      response = Response.ok((Object) out); 

      response.header("Content-Disposition", 
        "attachment; filename=\"" + filetype + " - " + new Date().toString() + ".zip\""); 

      out.flush(); 
      out.close(); 


     catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     System.out.println("End"); 
     return response.build(); 
    } 

這是給我下面的錯誤: javax.ws.rs.WebApplicationException:com.sun.jersey.api.MessageException:消息正文作家Java類java.io .FileOutputStream和Java類型java.io.FileOutputStream和MIME媒體類型application/zip未找到

+1

你爲什麼將FileOutputStream設置爲響應體? – Gimby

+0

@Gimby你說得對。我刪除了那一點,我只是傳遞字節數組作爲Response.ok((對象)工作簿)。該zip文件是可下載的。 – ronn

回答

2

您尚未添加MIME類型的響應。處理此響應時,您的瀏覽器會感到困惑。它需要響應內容類型。要設置響應內容類型爲您的回覆,添加如下代碼,謝謝

  response.setContentType("application/zip"); 

  response = Response.ok((Object) out); 

+0

好的,但是這個錯誤是由服務器產生的,而不是瀏覽器產生的。 – Gimby