I'm trying to download an .exe from a springboot application with Reactjs UI.
The problem that I'm having is, the download doesn't show progress immediately at the time of downloading the blob. Download starts only after the blob is completely downloaded and directly displays as download is completed. Using the API call directly in the URL works fine, but using Axios call, I'm facing this issue. Should I be handling the response in javascript different way?
Here's my backend code:
private static final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private static final Resource resource = resolver.getResource("abc/ABC.exe");
public ResponseEntity<ByteArrayResource> clientSetup() {
try {
byte[] templateContent = org.springframework.util.FileCopyUtils.copyToByteArray(resource.getInputStream());
ByteArrayResource inputStream = new ByteArrayResource(templateContent);
if(inputStream.exists()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "ABC.exe"+ "\"")
.contentLength(inputStream.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(inputStream);
}else {
throw new Exception();
}
}catch(Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
return new ResponseEntity<ByteArrayResource >(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
UI :
try {
const response = yield axios.get("/download/abc", {
responseType: "arraybuffer"
});
let blob = new Blob([response.data], {
type: response.headers["content-type"]
});
let downloadUrl = window.URL.createObjectURL(blob),
filename = "",
disposition = response.headers["content-disposition"];
if (disposition && disposition.indexOf("attachment") !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, "");
}
}
let a = document.createElement("a");
if (typeof a.download === "undefined") {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} catch (error) {
console.log(error);
}
}