'How do I return a byte array as response using spring boot and ajax?
I am trying to create a page that will download a file from a data stream. I am able to get the byte stream and I want to return this to client side to save it as file.
I tried the code below however, the file that is being saved is corrupted. The download process also is too quick that I think it is not downloading properly..
Java code:
@RequestMapping(value = /download, method=RequestMethod.POST)
public ResponseEntity<ByteArrayResource> download() {
byte b[] = <retrieving byte data array here>;
ByteArrayResource resource = new ByteArrayResource(b);
ResponseEntity<ByteArrayResource> r = ResponseEntity.ok()
.header("Content-type", "application/octet-stream")
.header("Content-disposition", "attachment; filename=\"test.mp4\"")
.contentLength(resource.contentLength())
.body(resource);
return r;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Javascript code:
$('#download').click(function() {
$.ajax({
type: "POST",
url: "/download",
data: {}
}).done(function(data) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([data], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "test.mp4";
a.click();
}
}).fail(function(data) {
});
});
Hope you guys could help me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
