Utilizing AJAX to Load JSON File Compressed with GZIP

I utilized the gzip algorithm to compress a JSON file, following this method (source: 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;
    }

The JSON content is returned as follows:

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);

When attempting to access the JSON object using AJAX code like so:

$.ajax({
    type : 'GET',
    url : url,
    headers : {'Accept-Encoding' : 'gzip'},
    dataType : 'text',

The result displayed is binary data instead of the uncompressed JSON string. Any recommendations on how to resolve this issue? Keep in mind that the browsers I am using (Internet Explorer, Chrome, Firefox) support gzip, as all my static contents compressed by Apache are rendering correctly.

Answer №1

Instead of using:

response.sendRedirect(filePathurl);

You are initiating a new request/response cycle. This separates the headers you specified from the actual file being sent.

Instead of redirecting, you should load the file and stream it within the same response.

Observe this behavior using Fiddler or another request viewer.

Answer №2

The ability to override Accept-Encoding from the browser or JavaScript has been restricted.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

Looking for assistance with iterating through various layers of nested arrays on a map

Feeling completely stumped after exhausting all my options, I've finally reached out for help. I just can't figure it out... My blog posts are structured like this: const posts = [ { section: 'one', title: [ 'third', &apo ...

Is it possible to set up a local version of the Firebase database for development testing?

Can the actual code on Firebase database be avoided during development by running a local instance and developing using that, similar to other MongoDB and MySQL databases? ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

What is the method for editing individual rows in a data table in Spring MVC when the edit button is clicked?

Every time I click on <a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>, I only get a modal on the first row click, and it appears empty. I've searched through many internet resources, but none of them pro ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

Issue: [ng:areq] The argument 'HelloController' is not defined as a function, it is displayed as undefined

Struggling to integrate Angular with Django has been quite a challenge for me. After finally managing to make it work, I encountered yet another error. Each time I load the application, the following error message pops up: Error: [ng:areq] Argument ' ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

Storing the value from the INPUT field in the state of React is not permitted

I'm attempting to retrieve the user input value from the INPUT field and update it in the corresponding state. However, no matter what I type in the field, it doesn't get set to the state. createForm(x){ var dx = 'd'+x let da ...

Experiencing the issue of receiving `undefined` when trying to access res.query with a JSON query string using

Utilizing qs for constructing JSON-based query parameters for my REST API request: On the client side: import qs from "qs"; let query = { dateTime: { $gte: 1664557995000 } }; let q = qs.stringify(query); let url = "http://lo ...

Disable Jquery toolstrip while the menu is open

Currently, I am utilizing the jQuery toolstrip plugin in my project. I have a requirement to disable it whenever the sidebar menu is opened. Below are the HTML codes for my menu with li tags: <div class="sidebar-wrapper" id="sidebar-wrapper"> <ul ...

How should you correctly display the outcome of a mathematical function on a data property in a v-for loop in VueJS?

Recently, I've been developing a dice roller using Vue for a game project. The approach involves looping through different types of dice with v-for to create buttons and display the result in an associated div element. However, despite correct console ...

What is the best way to extract data using a specific key in a JSON object?

Currently, I am following a tutorial on MongoDB from this website. In the tutorial, there is an instruction provided as follows: $cursor = $collection->find(array("author" => "shreef")); foreach ($cursor as $document) { print_r($document) } The ...

The ng-repeat function in AngularJs does not display the data despite receiving a successful 200 response

As part of my academic assignment, I am exploring Angularjs for the first time to display data on a webpage. Despite receiving a successful http response code 200 in the Chrome console indicating that the data is retrieved, I am facing issues with displayi ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Ng-Grid error: Trying to access property 'on' of a null value

Currently, I am in the process of creating an angular.js directive that involves a JQuery dialog box containing a grid component. Directive Template: <div class="datasetsGrid" ng-grid="gridOptions"></div> The Issue Whenever I click on the " ...

Utilize Vue.js to sort by price bracket and category

Hello, I am currently new to working with Vue.js and I am attempting to create two filters - one for price range and the other for genre. Any guidance or assistance would be greatly appreciated. Below is a snippet of my code: ul class="filter-wrapper"&g ...

Setting the offset for panResponder with hooks: A step-by-step guide

While exploring a code example showcasing the use of panResponder for drag and drop actions in react native, I encountered an issue with item positioning. You can experiment with the code on this snack: The problem arises when dropping the item in the des ...