0

I am developing a web application and one of my use cases is for users to have the ability to upload and download files from the server. I'm using ReactJs and Spring Boot.

Front-End code:

 downloadFileClicked(id, fileName, fileType){
TestDataService.downloadFile(id)
.then(response=>{
  console.log(response)
  const file = new Blob(
    [response.data],
    {type: fileType}
  )
  
     let url = window.URL.createObjectURL(file)
     let a = document.createElement('a')
     a.href=url
   a.download= fileName
   a.click()
})
}

Back-End code:

@GetMapping("/downloadFile/{fileId:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable Long fileId, HttpServletRequest request ){
    
    //Load file as a resource
    DatabaseFile databaseFile = fileStorageService.getFile(fileId);
    
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(databaseFile.getFileType()))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+databaseFile.getFileName()+"\"")
            .body(new ByteArrayResource(databaseFile.getData()));
    
}

When the user clicks download - the file does indeed download and seemingly in the correct format but when each application tries to open the file I am faced with such errors as the file format is not supported or the file is corrupt.

The file data is being stored as a byte array in a MySQL database. I have tried a number of different methods to download the file but I have encountered the same error each time. Any help would be greatly appreciated!

JMD77
  • 1
  • Does this answer your question? [Spring returning image as ResponseEntity - image corrupt](https://stackoverflow.com/questions/31313303/spring-returning-image-as-responseentitybyte-image-corrupt) – Haytam Jun 30 '20 at 13:50
  • Thanks for the answer. Unfortunately still have the same issue after trying that method. I believe the issue lies in how I am handling the byte array data as when I use postman to test my API it returns the image fine. The issue arises when any application on my computer tries to open the file. – JMD77 Jun 30 '20 at 14:35

0 Answers0