Using JavaScript to save an XLSX file directly from an HTTP API server

I have a web service that returns an HTTP response with the following Content-Type:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

When I call this service using cURL and redirect the output to create a .xlsx file, everything works perfectly. However, when I try to save the file from JavaScript, it fails. Here is the code snippet I am using:

cURL:

$ curl -v -X POST <API_ENDPOINT> > a.xlsx ;# a.xlsx works fine

Javascript:

$http.post(<API_ENDPOINT>).then(function(response) {
          console.log(response);
          downloadFile(response.data, "b.xlsx")
});

var downloadFile = function(responseData, fileName) {
      var blob = new Blob([responseData], {
        type: 'application/vnd.ms-excel'
      });

      if (window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveBlob(blob, fileName);
      } else {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(blob);

        document.body.appendChild(a);
        a.style = 'display: none';
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      }
};

Although the file gets saved, the contents appear to be different from the one downloaded via cURL, even though the server sends the same file.

The content-length header value is consistent in both responses (cURL and JavaScript captured through Chrome DevTools), but the file size when redirected via cURL is 5.1k (almost matching the content-length value), while the file size of the file created by JavaScript is 8.5k, which is incorrect.

I have tried setting various content types like application/octet-stream, octet/stream,

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
when creating the blob, but none seem to resolve the issue.

I suspect that there may be something wrong with how I handle the content-type and blob creation, but I cannot pinpoint the exact problem. Any assistance would be greatly appreciated.

Answer №1

After some troubleshooting, I was able to identify the issue. In order for the $http.post method to handle binary responses correctly, an additional parameter must be specified. The modification that resolved the issue was:

$http.post(<API_ENDPOINT>, null, {responseType: 'arraybuffer'});

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

Change the background color of a table cell based on its value with the help of JavaScript

I am attempting to apply color to cells in an HTML table (generated automatically by Python and Django) based on the content of the cells. Below is my table. I want to specifically color the column "status". Whenever the word "Cloture" appears, I would li ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

In search of a jQuery parser for HTML strings that can accurately parse <a> links and <img> images

Is there a HTML string jQuery parser available, specifically for parsing <a> links and <img> images? Alternatively, I am looking for code that can extract all links and images from a HTML string, which can potentially be very large. For exampl ...

Definition file for TypeScript for the library "to$q"

I need some assistance with utilizing $q in my Angular application while writing it in TypeScript. I've been facing difficulties and attempted to define a type definition file like so: /// <reference path="../q/Q.d.ts" /> /// <reference path ...

What is the reason behind my Canvas loading only after I save the new code?

I'm currently facing an issue with loading an image into my canvas. The strange thing is, when I load the page, the image doesn't appear, even though the image src is logging correctly in the console. However, if I save my code and trigger a refr ...

Understanding the functionality of script tags during the PreRender phase is crucial

I am currently exploring the possibility of reading script tags within the PreRender event of a master page. I have been successful in extracting CSS links, but I am facing difficulties with script tags. The following code successfully retrieves CSS links ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

The Javascript function is triggered only upon the second click

My goal is to retrieve prescription details for a specific patient, with the results displayed in a modal window. However, I am encountering an issue where the first result is only obtained on the second click. Subsequent clicks display the results of the ...

When a function is required in the mongoose model schema file, the Mongoose.model('model_name') will result in an empty object being returned

Sorry if the title of my question is confusing, as I find it hard to articulate this issue. I have two files named matchedTransaction.js and player.js. sharedApi/player.js const MatchedTransactionModel = require('../models/matchedTransaction'); ...

The JavaScript function is not executing the Node.js code as expected

Currently, I am utilizing Twilio to send a sample message when running the provided code in the terminal: var accountSid = '...'; var authToken = '...'; var twilio = require('twilio'); var client = new twilio(acco ...

Troubleshooting: Issues with NodeJs / Google Firebase functions and string manipulation operations

I've developed a Google Assistant application that leverages various APIs to fetch and provide bus arrival timings for the local university. However, the API returns the arrival times in a string format as shown below: "2018-51-02T06:51:11" Attempte ...

Executing commands in the console using Playwright JS testing

We are looking to execute the command '$gui.dispatch('callBarcodeHandler', '98783083')' in the console during testing. An example scenario would be logging in and needing to send a command to scan a barcode. ...

Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable: @Injectable() export class ProductService { getAllProducts(): Observable<Product[]> { return this.http.get(' ...

Sending HTML data from jQuery via Ajax to PHP and receiving a response

I'm trying to post data from a span when clicked, but nothing happens. The span contains the number '4'. I am not sure about the syntax for doing this. <span style="color:#B00" id="PidClick">4</span> This is how I am attempting ...

There was an issue with d3 version 4: the function this.setAttribute() was not

I am attempting to update the provided example to be compatible with d3 version 4 http://bl.ocks.org/ameyms/9184728 Most of the code has been successfully converted, but I am encountering difficulties with the following function: this.el.transition().del ...

What is the best method for testing AngularJS cookies in an end-to-end test?

How can I test if cookies are properly set in Angular when using a simple service? It seems challenging to do so in an end-to-end test. The code snippet for testing is straightforward: var splashApp = angular.module('splashApp', ['ngCookie ...

Creating a stylish Go URL bar using HTML and CSS

Looking for some guidance in JavaScript as I am new to it. I want to create a go bar similar to the ones found at the top of browsers using HTML and JS. When the button is clicked, it should navigate to the URL entered in the box. Here's an example of ...

Opt for specific data by default when working with multi data series on c3 charts

Looking at this complex multi-data chart depicted in the image here: https://i.sstatic.net/Gpz52.png The C3 chart displayed all data series by default and visualized them together on the chart. Is there a method available to pre-select one or two data se ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

The ng-model in AngularJS with a filter is preventing me from making any changes

Here is a simple form I have created: <span>{{ entry.Date | amDateFormat: 'DD.MM.YYYY' }}</span> When the "edit" button is clicked, the `span´ is hidden and the form is shown: <input type="text" ng-model="entry.Date | amDateFo ...