java – 在Spring MVC REST中返回文件

前端之家收集整理的这篇文章主要介绍了java – 在Spring MVC REST中返回文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有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;
}
原文链接:https://www.f2er.com/java/127358.html

猜你在找的Java相关文章