Java – return files in spring MVC rest
•
Java
I have the rest service code. The following code returns a file. Now the problem is that I get an original response in the response body of the postman client. How can I convert it so that it can display the contents of the file to the client, and the goal is to return the file to the user 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; }
Solution
The following code solves my problem:
@RequestMapping(value = URIConstansts.GET_FILE,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,HttpStatus.OK); }else{ respEntity = new ResponseEntity ("File Not Found",HttpStatus.OK); } return respEntity; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码