Revert file to Spring MVC REST

I have a REST service code below the code that the file returns, now the problem is in the response body in the PostMan Client. I get a raw response, how can I convert it so that it displays the contents of the file for the client, the goal is to return the file to the user. The file name is "File1.jpeg"

code:

@RequestMapping(value = URIConstansts.GET_FILE, produces = { "application/json" }, method = RequestMethod.GET) public @ResponseBody ResponseEntity getFile(@RequestParam(value="fileName", required=false) String fileName,HttpServletRequest request) throws IOException{ ResponseEntity respEntity = null; byte[] reportBytes = null; File result=new File("/home/arpit/Documents/PCAP/dummyPath/"+fileName); if(result.exists()){ InputStream inputStream = new FileInputStream("/home/arpit/Documents/PCAP/dummyPath/"+fileName); byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("content-disposition", "attachment; filename=" + fileName); respEntity = new ResponseEntity(out, responseHeaders,HttpStatus.OK); }else{ respEntity = new ResponseEntity ("File Not Found", HttpStatus.OK); } return respEntity; } 
+6
source share
2 answers

The code below solved my problem:

 @RequestMapping(value = URIConstansts.GET_FILE, produces = { "application/json" }, method = RequestMethod.GET) public @ResponseBody ResponseEntity getFile(@RequestParam(value="fileName", required=false) String fileName,HttpServletRequest request) throws IOException{ ResponseEntity respEntity = null; byte[] reportBytes = null; File result=new File("/home/arpit/Documents/PCAP/dummyPath/"+fileName); if(result.exists()){ InputStream inputStream = new FileInputStream("/home/arpit/Documents/PCAP/dummyPath/"+fileName); String type=result.toURL().openConnection().guessContentTypeFromName(fileName); byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add("content-disposition", "attachment; filename=" + fileName); responseHeaders.add("Content-Type",type); respEntity = new ResponseEntity(out, responseHeaders,HttpStatus.OK); }else{ respEntity = new ResponseEntity ("File Not Found", HttpStatus.OK); } return respEntity; } 
+14
source

You need to use a different type of content instead of create = {application / json "}

Content Types

http://silk.nih.gov/public/ zzyzzap.@www.silk.types.html

If it still does not work, try to get HttpServletResponse and write the data of your file to Stream using response.setContentType ();

Note. I recently used response.getOutputStream to write an Excel file. For some reason, setting up didn't work for me.

You can also use Firebug in firefox to view response headers.

+2
source

All Articles