I need to develop a REST API endpoint to serve a file. So I implement the following code with help of other resources
@GetMapping(path = Array("/download"))
def downloadFile() : ResponseEntity[Resource] = {
var file: File = new File("src/main/scala/testFile.txt")
if(file.exists()){
val path = Paths.get(file.getAbsolutePath)
val resource = new InputStreamResource(new FileInputStream(file))
// val resource = new ByteArrayResource(Files.readAllBytes(path))
val responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=results.txt")
responseHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate")
responseHeaders.add("Pragma", "no-cache")
responseHeaders.add("Expires", "0")
println(resource)
ResponseEntity.ok()
.headers(responseHeaders)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}else{
ResponseEntity.notFound().build()
}
}
and also from react side implemented as below
var win = window.open('_blank');
var filePath = ".../download"
downloadFile(filePath, function (blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}
the exception is coming from the scala side it throws
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class org.springframework.core.io.InputStreamResource] with preset Content-Type 'application/octet-stream']
any suggestions for fix this issue. thank you