0

I have requirement in my project with which when user select multiple file to download, we need to zip them and then make them to download. We have tested that the Struts2 action is listing all the file correctly and passing them to the UI. We've verified that the files are list on to UI correctly but when the blob statement executed, it made the zip file corrupted. Here is the my code snippet. Can anyone please help here?

Code:

   $.ajax({
      url: url,
      data: data,
      type: "POST",
      async: true,
      success: function (data) {
        var binaryData = [];
        binaryData.push(data);
        var link=document.createElement('a');
        link.href =window.URL.createObjectURL(**new Blob(binaryData, {type: "application/zip"**}));
        link.download = "User Reports Data Files.zip"
        link.click();
      },
      error: function (request, status, error) {
      }
    }); 

1 Answer 1

1

Two answers for you:

  1. I don't think you can reliably download binary data with jQuery's ajax function (but I could be mistaken). If you want to download binary, use fetch, which has support for reading the response as a BLOB built in.

  2. It would be simpler to have a zero-height iframe on your page with name="download-target" and then have a form target="download-target method="post" and submit that instead of using ajax. Be sure the response includes a Content-Disposition header, for instance:

    Content-Disposition: attachment; filename="User Reports Data Files.zip"
    

#2 is simpler and lets the browser handle the download in its normal, thoroughly-tested way.

But here's a sketch of #1:

fetch(url, {
    method: "POST",
    body: data
})
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.blob();
});
.then(blob => {
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = "User Reports Data Files.zip"
    link.style.display = "none";         // Firefox wants this
    document.body.appendChild(link);     // ""
    link.click();
    setTimeout(() => {                   // ""
        document.body.removeChild(link); // ""
    }, 10000);                           // ""
})
.catch(error => {
    // Handle/report the error
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.