使用Restful服务下载zip文件

时间:2014-04-14 10:18:01

标签: java rest download zip

我尝试使用restful服务在java中创建和下载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 个答案:

答案 0 :(得分:1)

您尚未添加回复的MIME类型。处理此响应时,您的浏览器会感到困惑。它需要响应内容类型。要为响应设置响应内容类型,请添加以下代码

          response.setContentType("application/zip");

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

感谢。