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

Browsersync in Gulp keeps triggering numerous reloads every time a file is changed

As I utilize browsersync with Gulp for running specific tasks upon file changes, I notice that each time I save a file, my terminal displays 10+ [BS] Reloading Browsers... messages and the overall performance suffers. Below is an outline of my gulpfile: ...

Can Angular be used to dynamically filter a JSON object to display only the fields that match a specified filter text?

Sorry if this question has already been asked; I couldn't find the solution. Here is my issue: In my Angular app, I am retrieving a complex JSON object from a web service. I then present this JSON object to the user in tree format using ngx json vie ...

Inject a directive attribute dynamically into an element using another directive, and ensure the initial directive is set to 'active.'

Let me explain in more detail. I am utilizing the tooltip directive from the UI Bootstrap suite, which allows me to attach a tooltip to an input element like this: <input type="text" ng-model="inputModel" class="form-control" placeholder=" ...

Deleting elements in an array that have a last digit of 1 - how is it done

I am struggling to remove array elements with a name field that ends in 1. Given Input: { "foo": "bar", "data": { "code": "abc123", "items": [ { "name": "exp1" }, { "name": "exp2" }, { "na ...

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

Exploring different pages in an Ionic and AngularJS mobile application

I am brand new to the world of Ionic and AngularJS. I have just started working on a simple project but have hit a roadblock. My goal is, To create a login page and a register page. When a user clicks the register button on the login page, they should be ...

The error message "Cannot call expressjs listen on socket.ip" indicates that there

Currently working on a project involving websockets, but encountering an error in the code below: TypeError: require(...).listen is not a function Here's what I have tried so far: const app = require("express")(); const port = 3800; const ...

Having trouble parsing a basic JSON file in Extjs's treepanel widget

I am facing an issue with loading a simple JSON file where nodes are nested inside the "data" attribute as shown below. My expectation is to retrieve two nodes with text AAA and BBB, but instead, I am getting a tree structure with empty nodes that have inf ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

What is the best way to customize the style of a react.js component upon its creation?

Is there a way to set the style of a react.js component during its creation? Here is a snippet of my code (which I inherited and simplified for clarity) I want to be able to use my LogComponent to display different pages of a Log. However, in certain ins ...

Automatically populate fields with pre-filled information

In my database, I have a table named "Produits": public function up() { Schema::create('produits', function (Blueprint $table) { $table->id(); $table->string('reference')->nullable(); ...

Why does JavaScript function flawlessly in FireFox, yet fails completely in other web browsers?

When it comes to browsing, FireFox is my go-to browser, especially for testing out my website Avoru. However, I recently encountered an issue when checking the functionality of my code on other major browsers like Google Chrome, Opera, and Safari. It seems ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...