0

我正在尝试实现一个简单的 servlet,它返回一个捆绑在应用程序内部的 zip 文件(简单资源)

所以我在服务器端实现了以下方法:

@GET
@Path("{path}/{zipfile}")
@Produces("application/zip")
public Response getZipFile(
        @PathParam("path") String pathFolder,
        @PathParam("zipfile") String zipFile) IOException {
    String fullPath= String.format("/WEB-INF/repository/%s/%s",
            pathFolder, zipFile);
    String realPath = ServletContextHolder.INSTANCE.getServletContext()
            .getRealPath(fullPath);
    File file = new File(realPath );

     ResponseBuilder response = Response.ok((Object) file);
     return response.build();
}

当我从浏览器调用此方法时,会下载 zip 文件,其大小与服务器中原始 zip 的字节数相同。

但是,当我使用客户端代码中的简单 XMLHttpRequest 调用它时:

        var oXHR = new XMLHttpRequest();
        var sUrl = "http://localhost:8080/path/file.zip"
        oXHR.open('GET', sUrl);
        oXHR.responseType = 'application/zip';
        oXHR.send();

我可以在 chrome 中的开发工具的网络选项卡中看到内容大小更大,并且我无法处理此 zip 文件(例如 JSzip 无法识别它)。

似乎在我的响应和来自的最终响应之间的某个地方,org.glassfish.jersey.servlet.ServletContainer写入了一些额外的字节/对文件进行了一些编码。

你能帮忙吗?

最好的问候, 马克西姆

4

1 回答 1

0

当您使用 ajax 请求时,浏览器需要文本(默认情况下)并将尝试从 UTF-8 解码它(破坏您的数据)。尝试使用oXHR.responseType = "arraybuffer";: 这样,浏览器不会更改数据并为您提供原始内容(将在 中oXHR.response)。

此解决方案不适用于 IE 6-9:如果您需要支持它,请查看 JSZip 文档:http ://stuk.github.io/jszip/documentation/howto/read_zip.html

如果这不是正确的解决方案,请尝试直接下载 zip 文件(不涉及任何 js 代码)以检查问题是来自 js 端还是来自 java 端。

于 2014-06-15T19:07:30.603 回答