在Spring MVC REST中返回文件

我有下面的REST服务代码,该代码返回一个文件,现在问题出在PostMan客户端的响应正文中,我得到了原始响应,该如何转换它以便将文件内容显示给客户端,目标是将文件返回给用户。文件名是“

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, 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;

}

以上是 在Spring MVC REST中返回文件 的全部内容, 来源链接: utcz.com/qa/423268.html

回到顶部