java - 在 Spring MVC REST 中返回文件

标签 java spring rest http spring-mvc

我有 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;
}

关于java - 在 Spring MVC REST 中返回文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641231/

相关文章:

java - 无法删除或更新父行 : a foreign key constraint fails and Entity hierarchy mustn't change

rest - 在Delphi XE10.1中使用/解析curl

rest - 通常在 ExtJS 应用程序上转义 HTML 的最佳方法是什么?

java - 根据键返回列表过滤HashMap

java - 在 maven 构建时指定 env 依赖属性文件

Java 8 使用自定义收集器进行分组?

java - 从 EntityManagerFactory 发出连接 EntityManager

RESTFul Flat Hierarchy vs. Dynamic Hierarchy for Search Resource

java - 使用 Apache PDFBox 生成 unicode pdf

java - 将值从适配器传递到导航组件中的 BottomNavigationView fragment