【问题标题】:Loading GZIP JSON file using AJAX使用 AJAX 加载 GZIP JSON 文件
【发布时间】:2013-03-23 23:30:48
【问题描述】:

我使用以下算法压缩了 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;
    }

我正在返回 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 gzip 压缩的静态内容都正确呈现。

【问题讨论】:

    标签: javascript ajax json gzip


    【解决方案1】:

    通过使用:

    response.sendRedirect(filePathurl);
    

    您正在创建另一个请求/响应。您定义的标头不再与实际发送的文件相关联。

    您需要加载文件并在同一响应中流式传输,而不是发送重定向。

    使用 Fiddler 或其他请求查看器查看此内容。

    【讨论】:

    • 感谢您的回复。 Fiddler 确认你的观点;我也尝试了转发方法,其中提琴手显示正确的标题,当我查看未压缩的文本时,我可以看到 JSON;但 AJAX 代码不会将输出读取为 JSON。我正在寻找解决方案(如果可行)以避免读取和流式传输文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2020-11-03
    相关资源
    最近更新 更多