我有REST服务代码下面的代码返回一个文件,现在问题是在PostMan客户端的响应体中我得到一个原始响应,我怎么能转换它以便它向客户端显示文件的内容,目标是将文件返回给用户.File Name是“File1.jpeg”
码:
@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; }
解决方法
下面的代码解决了我的问题:
@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; }