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 -
- 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?
- What is the proper way to handle file download with error handling?