1

I have one GET request which returns a JAR file, which I need to download. Easiest way to to the downloading part is to let browser handle the downloading part as follows :

window.location.href = URL

But, that does not work for error handling (handling server errors).

Alternatively, I found another way which creates blob object, and creates Object URL from that object and assigns it to anchor tag for downloading -

callSomeURL().then((res) => {
  const blob = new Blob([res._body], { type: res.headers.get('content-type') 
  });
  const url = window.URL.createObjectURL(blob);
  const linkElement = document.createElement('a');
  linkElement.setAttribute('href', url);
  linkElement.setAttribute('download', 'test jar file');
  const clickEvent = new MouseEvent('click', {view: window});
  linkElement.dispatchEvent(clickEvent);
}).catch((error) => error handling part)

content type is 'application/java-archive' res._body is encoded string.

Problem with this is that the file downloaded is invalid / corrupt. (Not sure whats wrong with the implementation).

I have 2 questions here -

  1. What is the proper way to create a blob object? Is it created using the encoded data that the response returns or the URL of the request?
  2. What is the proper way to handle file download with error handling?
Awadhoot
  • 737
  • 6
  • 19

1 Answers1

0

Your problem is that the response you get is plain/text. So when you generate your Blob, it's still plain text, and the binary data got mangled when converted to utf16 by javascript.

To avoid that, you can request it as a blob directly from your ajax call.

With XMLHttpRequest, you can set the responseType parameter of your XHR object:

var xhr = new XMLHttpRequest();
xhr.open('get', your_url);
xhr.responseType = 'blob';
xhr.onload = function() {
   var blob = xhr.response;
   // do something with the blob
   var url = URL.createObjectURL(blob);
   anchor.href = url
   anchor.click();
};
xhr.send();

With fetch API, you can call the blob() method of the Response object

fetch(your_url)
  .then(resp => resp.blob())
  .then(doSomethingWithBlob)
Kaiido
  • 123,334
  • 13
  • 219
  • 285