0

I'm trying to implement a simple servlet that returns a zip file that is bundled inside the application (simple resource)

So I've implemented the following method in the server side:

@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();
}

When I call this method from the borwser, the zip file is downloaded and its size is the same number of bytes as the original zip in the server.

However, when I call this using a simple XMLHttpRequest from my client side code:

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

I can see in the Network tab of the Developer tools in chrome that the content size is bigger, and I'm unable to process this zip file (for instance JSzip doesn't recognize it).

It seems like somewhere between my response and the final response from org.glassfish.jersey.servlet.ServletContainer, some extra bytes are written/ some encoding is done on the file.

Can you please assist?

Best Regards, Maxim

MaximD
  • 186
  • 2
  • 6

1 Answers1

0

When you use an ajax request, the browser expects text (by default) and will try to decode it from UTF-8 (corrupting your data). Try with oXHR.responseType = "arraybuffer"; : that way, the browser won't change the data and give you the raw content (which will be in oXHR.response).

This solution won't work in IE 6-9 : if you need to support it, check JSZip documentation : http://stuk.github.io/jszip/documentation/howto/read_zip.html

If it's not the right solution, try downloading directly the zip file (without any js code involved) to check if the issue comes from the js side or from the java side.

David Duponchel
  • 3,959
  • 3
  • 28
  • 36