【问题标题】:Download a zip file using Restful services使用 Restful 服务下载 zip 文件
【发布时间】:2014-04-14 10:18:00
【问题描述】:

我正在尝试使用 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 的消息正文编写器不是找到了

【问题讨论】:

  • 为什么要将 FileOutputStream 设置为响应正文?
  • @Gimby 你是对的。我删除了那个位,我只是将字节数组作为 Response.ok((object) workbook) 传递给响应。并且 zip 文件是可下载的。

标签: java rest download zip


【解决方案1】:

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

          response.setContentType("application/zip");

之后

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

谢谢。

【讨论】:

  • 好的,但是这个错误是服务器产生的,不是浏览器产生的。
  • 考虑使用 MediaType.APPLICATION_OCTET_STREAM。
猜你喜欢
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 2015-08-28
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多