2014-04-14 153 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