2014-06-15 26 views
0

我想實現一個簡單的servlet返回新澤西州的servlet返回zip文件,包含除響應發送

所以我實現以下是在應用程序內部捆綁一個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(); 
} 

當我打電話從borwser這種方法,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的最終迴應之間的某個地方,一些額外的字節被寫入/一些編碼在文件上完成。

您能否協助?

最好的問候, 馬克西姆

回答

0

當你使用一個Ajax請求,瀏覽器預計文本(默認),並會嘗試從UTF-8(破壞你的數據)進行解碼。 試用oXHR.responseType = "arraybuffer";:這樣,瀏覽器將不會更改數據併爲您提供原始內容(將在oXHR.response中)。

該解決方案將不會在IE 6-9的工作:如果你需要支持它,檢查JSZip文檔:http://stuk.github.io/jszip/documentation/howto/read_zip.html

如果這不是正確的解決方案,嘗試直接下載壓縮文件(沒有任何js代碼參與)來檢查問題是來自js方面還是來自java方面。

相關問題