在Spring MVC REST中返回文件 [英] Return file in Spring MVC REST

查看:144
本文介绍了在Spring MVC REST中返回文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有REST服务代码下面的代码返回一个文件,现在问题是在PostMan客户端的响应主体中我得到一个原始响应,我怎么能转换它以便它显示文件的内容到客户端,目标是将文件返回给用户.File Name是File1.jpeg

I have the REST Service Code Below code which returns a File ,now the problem is in the response body on the PostMan Client I get a raw response ,how can I can convert it so that it displays the contents of the file to the client ,Goal is to return a file to the user .File Name is "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;

}


推荐答案

代码下面解决了我的问题:

The code below solved my problem:

@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中返回文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆