[英]Loading GZIP JSON file using AJAX
我使用下面的算法gzipped json文件(來自: java gzip不能保留原始文件的擴展名 )
private static boolean compress(String inputFileName, String targetFileName){
boolean compressResult=true;
int BUFFER = 1024*4;
byte[] B_ARRAY = new byte[BUFFER];
FileInputStream fins=null;
FileOutputStream fout=null;
GZIPOutputStream zout=null;
try{
File srcFile=new File(inputFileName);
fins=new FileInputStream (srcFile);
File tatgetFile=new File(targetFileName);
fout = new FileOutputStream(tatgetFile);
zout = new GZIPOutputStream(fout);
int number = 0;
while((number = fins.read(B_ARRAY, 0, BUFFER)) != -1){
zout.write(B_ARRAY, 0, number);
}
}catch(Exception e){
e.printStackTrace();
compressResult=false;
}finally{
try {
zout.close();
fout.close();
fins.close();
} catch (IOException e) {
e.printStackTrace();
compressResult=false;
}
}
return compressResult;
}
我正在返回JSON
response.setHeader("Content-Type", "application/json");
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Vary", "Accept-Encoding");
response.setContentType("application/json");
response.setHeader("Content-Disposition","gzip");
response.sendRedirect(filePathurl);
要么
request.getRequestDispatcher(filePathurl).forward(request, response);
嘗試使用AJAX代碼訪問JSON對象,如下所示:
$.ajax({
type : 'GET',
url : url,
headers : {'Accept-Encoding' : 'gzip'},
dataType : 'text',
我看到的輸出是二進制數據,而不是解壓縮的JSON字符串。 有關如何使這項工作的任何建議? 請注意,我正在使用的瀏覽器(IE,Chrome,FF)支持gzip,因為我的所有靜態內容都被Apache正確呈現。
通過使用:
response.sendRedirect(filePathurl);
您正在創建另一個請求/響應。 您定義的標頭不再與實際發送的文件相關聯。
您需要加載文件並將其流式傳輸到同一響應中,而不是發送重定向。
使用Fiddler或其他請求查看器來查看此內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.