I am building a REST API in Spring Boot for uploading and fetching file from the server, I want to upload various types of file that can either be text,image,audio,video,etc..
While uploading there is no problem, but when I want to display the file on my web page, on content is appearing, but I am getting the data from the server as a raw data.
I want to put that data into URL.createObjectURL() and then redirect to the URL which is generated.
There are some screenshots which I am uploading.
This is the data when I do console.log(response);
The code which I am using for AJAX
var form = new FormData();
form.append("qualifiedFilePath", "E://files/test.png");
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:8081/callTransaction/file",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"Accept": "image/png",
"data": form
};
$.ajax(settings).done(function(response) {
console.log(response);
const objectURL = URL.createObjectURL(new Blob([response], {
"type": "image/png"
}));
console.log(objectURL);
});
I get the URL: blob:http://localhost:8080/81c9fbde-5e84-400e-8d92-5da6fc02c7ef
Output:
The Source Code in Spring Boot:
Controller:
@PostMapping(path="/file")
@CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity<Resource> loadFile(@RequestPart("qualifiedFilePath") String qualifiedFilePath, HttpServletRequest request)
{
return ctbl.loadFile(qualifiedFilePath,request);
}
BusinessLogic:
public ResponseEntity<Resource> loadFile(String qualifiedFilePath, HttpServletRequest request)
{
Resource file=null;
if(qualifiedFilePath==null)
{
return new ResponseEntity<Resource>(file,HttpStatus.BAD_REQUEST);
}
try {
file=ctdi.loadFile(qualifiedFilePath);
} catch (MalformedURLException e) {
return new ResponseEntity<Resource>(file,HttpStatus.INTERNAL_SERVER_ERROR);
}
if(file==null)
{
return new ResponseEntity<Resource>(file,HttpStatus.NO_CONTENT);
}
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(file.getFile().getAbsolutePath());
} catch (IOException ex) {
return new ResponseEntity<Resource>(file,HttpStatus.INTERNAL_SERVER_ERROR);
}
if(contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
DAO:
@Override
public Resource loadFile(String qualifiedFilePath) throws MalformedURLException {
Path filePath = Paths.get(qualifiedFilePath);
Resource resource = new UrlResource(filePath.toUri());
return resource;
}