The combination of JAX-RS, AJAX, and JavaScript's blob object is unable to successfully download the file

Attempting to download a file using javascript's Blob object has resulted in some unexpected behavior. Initially, I am utilizing JAX-RS to send the file from the backend. Below is the code snippet:

    Workbook wb = new HSSFWorkbook();

    //creating workbook...

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        wb.write(bos);
        bos.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
    byte[] bytes = bos.toByteArray();
    return Response.ok(bytes).header("Content-Disposition", "attachment; filename=" + "test.xls").build();

The 'bos' variable represents a 'ByteArrayOutputStream' object created from the Apache POI workbook. When downloading the file using the regular method by pointing the browser to the JAX-RS resource, everything works fine. However, when attempting to implement the solution provided at this link, the downloaded file is corrupted.

Upon debugging in Chrome's console, an observation was made regarding the difference in size between the response and Blob objects while converting the response to Blob format. The response size shows as 4096 bytes:

Date: Tue, 10 Feb 2015 17:32:27 GMT
Server: WildFly/8
Connection: keep-alive
X-Powered-By: Undertow/1
Content-Length: 4096
Content-Disposition: attachment; filename=test.xls
Content-Type: application/vnd.ms-excel

However, upon performing the conversion with

var blob = new Blob([response], { type: type });
, the Blob object size increases to 7836 bytes. This discrepancy in sizes raises questions about why this issue occurs and what causes it.

The problematic behavior was consistent not only in Chrome Version 40.0.2214.111 (64-bit) but also in Firefox 35.0.1.

Thank you for any insights or assistance in addressing this matter.

P.S. The complete client-side code related to the issue mentioned above can be found on this Stack Overflow question page: SO Question.

Answer №1

Your binary information will be transformed into text, resulting in data corruption.
At this time, jQuery.Ajax is unable to perform a typed ajax request, which is necessary for your situation. Therefore, you will have to utilize plain XMLHttpRequest and adjust the responseType to blob. Subsequently, XMLHttpRequest.response will represent the data as a blob.

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

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

When clicking on the register button in Node.js, no activity is initiated

Once upon a time, there was a humble express.js app that needed to establish a connection with a mysql database and retrieve user information for registration within the said database. Despite successfully connecting to the database, nothing would happen w ...

Merge two arrays of objects containing Google Map coordinates

I am facing a challenge with merging two object arrays that have similar values. var Cars = [{ lat: 42, lng: -72 }, { lat: 40.7127837, lng: -74.0059413 }, { lat: 40.735657, lng: -74.1723667 }]; var Trucks = [{ lat: 43, lng ...

Sequelize: Establishing association upon saving without the need to retrieve another object

Suppose I have two tables, parent and child, where the parent has multiple children. They are properly mapped in Sequelize. Now, I need to add a new child to an existing parent. However, I do not have access to the parent instance, only its id. I am aw ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Guide on including the angular value (id) in conjunction with repeating data-target for executing a function

I have the following code snippet. Now, I am trying to pass a dynamic AngularJS variable, specifically the id of a repeating list. The button in question is used for deactivation purposes, and upon clicking it, a confirmation box pops up. Upon confirming ...

What is the method for including word boundaries in a regex constructor?

export enum TOKENS { CLASS = 1, METHOD, FUNCTION, CONSTRUCTOR, INT, BOOLEAN, CHAR, VOID, VAR, STATIC, FIELD, LET, DO, IF, ELSE, WHILE, RETURN, TRUE, FALSE, NULL, THIS } setTokenPatterns() { let tokenString: s ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

Moving from traditional web pages to a mobile application using NextJS has brought about the error "rest.status is

Currently, I am in the process of upgrading from Next 13.2.5 to version 14.1.0 and switching to using app/api/example/route.js instead of pages/api/example.js. After making these changes, I encountered an error stating TypeError: res.status is not a funct ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

The argument provided, which is of type 'any[]', cannot be assigned to a parameter of type 'A' because the property 'a' is missing in the 'any[]' type

As a newcomer to TypeScript, I am currently trying to grasp the workings of interfaces within a Class Method of a React Component. Despite creating a simple case for it, I am encountering errors similar to those described in this post. I would greatly app ...

Angular implementation of checkboxes to streamline data filtering

I am currently displaying FreeEvents using a checkbox and passing the value to the filter as filter:filterFreeEvent, which is working perfectly fine. However, I would like to avoid passing the value in the filter and instead use a change event of a checkb ...

Using() multiple connections with identical models in redux-orm

My objective is to create a scenario where a Member can have both followers and followings in their list. ...

Ng-If Doesn't Work in the Current View

I'm having trouble updating the ng-if in my HTML code below: <div id="shyBoxII" ng-if="robot.robot" ng-class="background"> <div class="row"><i class="fa fa-user-plus"></i></div> <div class="row"><i clas ...

Ensure that CSS transformation rotation always moves in a clockwise direction without surpassing 360 degrees

As I work on designing a clock, I have implemented a combination of JS and CSS to create a seamless animation for the clock's "hands." This involves converting seconds, minutes, and hours into their corresponding degrees in the analog clock: function ...

Managing the CCAvenue response within an Angular JS 2.0 application

Currently, I am utilizing AngularJS 2.0 as the client-side application to interact with ASP.Net Core for server calls. Within this setup, I have implemented CCAvenue seamless integration kit to generate encrypted requests using server calls, including a su ...

Choosing the Right Project for Developing HTML/Javascript Applications in Eclipse

Whenever I attempt to build a webpage using eclipse, I am presented with two choices: -- A Javascript project -- A Static web project If I opt for the former, setting up run to open a web browser can be quite challenging. If I decide on the latter ...

Refresh a webpage content dynamically without the need to reload the entire page

How can I implement YouTube's page navigation system that does not require the entire page to reload when switching pages? Do I need to incorporate Javascript or utilize an API for this functionality? ...

Does the presence of a URL prefix (www or no www) impact the Jquery AJAX request to fetch JSON data?

Today, I encountered an unusual issue with JQuery that has me stumped and looking for some assistance. I dedicated most of the day to figuring out why the AJAX 'success' function in JQUERY was not being triggered when receiving JSON from the ser ...

Understanding the distinction between deleting and nullifying in JavaScript

var obj = {type: "beetle", price : "xxx", popular: "yes" ,.... }; If I want to remove all the properties from obj, what is the correct way to do it? Should I use delete obj.type; delete obj.price; delete obj.popular ... and so on. Or should I set ob ...