javascript 使用 AJAX 加载 GZIP JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15768047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading GZIP JSON file using AJAX
提问by ad-inf
I have gzipped json file using below algorithm (from: java gzip can't keep original file's extension name)
我使用以下算法压缩了 json 文件(来自: java gzip can't keep original file's extension name)
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;
}
I am returning the JSON
我正在返回 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);
or
或者
request.getRequestDispatcher(filePathurl).forward(request, response);
Trying to access the JSON object using AJAX code as below:
尝试使用 AJAX 代码访问 JSON 对象,如下所示:
$.ajax({
type : 'GET',
url : url,
headers : {'Accept-Encoding' : 'gzip'},
dataType : 'text',
The output I see is the binary data, not the decompressed JSON string. Any suggestion on how to make this work? Note that the Browsers I am using (IE, Chrome, FF) supports gzip as all my static contents which are gzipped by Apache are rendered correctly.
我看到的输出是二进制数据,而不是解压后的 JSON 字符串。关于如何进行这项工作的任何建议?请注意,我使用的浏览器(IE、Chrome、FF)支持 gzip,因为我所有由 Apache 压缩的静态内容都正确呈现。
回答by BNL
By using:
通过使用:
response.sendRedirect(filePathurl);
You are creating another request/response. The headers you have defined are no longer associated with the file that actually gets sent.
您正在创建另一个请求/响应。您定义的标头不再与实际发送的文件相关联。
Rather than sending a redirect, you need to load up your file and stream it in the same response.
您需要加载文件并在同一响应中流式传输它,而不是发送重定向。
Use Fiddler or another request viewer to see this.
使用 Fiddler 或其他请求查看器来查看。