Having trouble turning octet-stream response data into a downloadable Zip file

I've been attempting to download a Zip file that contains JSON files through an AJAX GET request.

Here is the format of the response headers:

Connection: keep-alive
content-disposition: attachment;filename=exportedFiles_ 1.6.0_20200731160652.zip
Content-Length: 4496
Content-Type: application/octet-stream
Date: Fri, 31 Jul 2020 10:36:52 GMT

Preview of the data in the Network tab:

https://i.sstatic.net/yHlNk.png

The AJAX call and success function look like this:

$.ajax({
      type: "GET",
      url: "/download/" ,
      async: false,
      success: function (data,status, xhr) {          
      var filename = xhr.getResponseHeader('content-disposition').split("filename=")[1];;
      var blob = new Blob([data], {type: "octet/stream"})
       saveAs(blob, filename); 
      }
    });

Although it successfully saves the Zip file, when I try to open it, I get an error message saying "Windows cannot open the folder, The compressed Zip is invalid".

https://i.sstatic.net/XjhJ9.png

Answer №1

To handle the Received document using Axios, with data in the format of `octect-stream` which may appear strange like `PK something JbxfFGvddvbdfbVVH34365436fdkln` as its octet stream format, ensuring that creating a file with this data may lead to corruption. Using `{responseType: 'blob'}` will convert the data into a readable format.

axios.get("URL", {responseType: 'blob'})
     .then((r) => {
         let fileName =  r.headers['content-disposition'].split('filename=')[1];
         let blob = new Blob([r.data]);
         window.saveAs(blob, fileName);             
      }).catch(err => {
        console.log(err);
      });

If you have attempted solutions that fail, such as trying to save a file as zip using window.saveAs(blob, 'file.zip'), consider:

const downloadFile = (fileData) => {
    axios.get(baseUrl+"/file/download/"+fileData.id)
        .then((response) => {
            console.log(response.data);
            const blob = new Blob([response.data], {type: response.headers['content-type'], encoding:'UTF-8'});
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = 'file.zip';
            link.click();
        })
        .catch((err) => console.log(err))
}
const downloadFile = (fileData) => {
axios.get(baseUrl+"/file/download/"+fileData.id)
    .then((response) => {
        console.log(response);
        const blob = new Blob([response.data], {type:"application/octet-stream"});
        window.saveAs(blob, 'file.zip')
    })
    .catch((err) => console.log(err))
}
function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    };

    return bytes;
}

Alternatively, another succinct solution is:

window.open("URL")

This approach may cause unnecessary tabs to open and require users to allow popups to work with this code. For scenarios where multiple files need to be downloaded simultaneously, it is advisable to go with the first solution or explore other alternatives.

Answer №2

To specify the response type as arraybuffer, use the following code:

dataType: '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

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Performing an AJAX call every half-hour using JavaScript

I am looking to implement an ajax request every 30 minutes using JavaScript. Specifically, for the user currently logged in, I aim to retrieve any notifications that have a start date matching the current time. These notifications are set by the user with ...

CKEditor Missing Plugin Icon for YouTube Video Embedding

After following the instructions on how to add a Youtube plugin in CKEditor and adding the code to config.js, I was disappointed to find that the youtube insert button did not show up on the toolbar. My next step was downloading and extracting the Youtube ...

Simple code styling tool

Seeking guidance to create a basic syntax highlighter using JavaScript or ClojureScript. While aware of existing projects like Codemirror and rainbow.js, I'm interested in understanding how they are constructed and looking for a simple example. Do th ...

How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figu ...

Organize WordPress loop posts based on tags in real-time

I have integrated a custom loop into my WordPress custom blog page to display all my posts. Here's how I did it: <section class="container blog-article-actu"> <div class="row"> <?php $the_query = ne ...

Loading dynamic CSS on WordPress frontend only

I am facing an issue with the dynamic css file in my WordPress theme that is loaded using Ajax. The problem is that it also loads this dynamic css file for the backend. Can someone help me modify my code so that it only loads the dynamic css file for the f ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Troubleshooting: Issue with Vue component template iteration

What is causing the issue with iterating inside the component template in the code above? <!DOCTYPE html> <html> <head> <title>Exploring Vue components</title> <script src="https://cdn.jsdelivr.net/npm/vue"></s ...

Form validation error: The error message for the password field could not be retrieved

I encountered an error in my firebug while working on a codeigniter site. The error message says "Unable to access an error message corresponding to your field name password". I have researched this issue and found that it usually occurs when there is an e ...

What's the issue with this fresh drag-and-drop directive clone?

Check out this jsfiddle where I used an angularjs directive to enable drag-and-drop functionality for a white square. View Fiddle 1 In another version of the fiddle, I added a green square and duplicated the directive. However, the squares do not drag an ...

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

Using jQuery: The procedure for sending JSON data in an AJAX post request

Currently, I am working on AJAX where I have created a post request as shown below: $.ajax({ 'url':'http://localhost/api/create/', 'method':'POST', 'dataType': 'json', 'co ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

Implementing jQuery AJAX in Rails 3 for enhanced functionality through the use of partial

In my Rails 3 project, I have an index view that displays several line items with their corresponding counts. The list looks like this: Name Count -------------- Item A 10 Item B 278 Item c 64 Although the list length can change dynamical ...

Tips for using jest toHaveBeenCalled with multiple instances

Currently, I am in the process of writing a test case for one of my functions. This function calls another function from a library, and I am attempting to mock this function (saveCall). Below is a snippet of the sample code in question: import { Call } fro ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Ways to instantly receive server (express) sent events from client (vue)

I am facing an issue with my Vue.js client not immediately listening to Express server sent events. Currently, the client only starts listening once the whole process is completed. This is a snippet of my Express Controller Code: exports.getFruits = (req ...