Return file in Spring MVC REST

前端 未结 2 1561
星月不相逢
星月不相逢 2021-02-14 02:13

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 th

相关标签:
2条回答
  • 2021-02-14 02:45

    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;
    }
    
    0 讨论(0)
  • 2021-02-14 03:00

    You need to use different content type instead of produces = { application/json" }

    Content-types

    http://silk.nih.gov/public/zzyzzap.@www.silk.types.html

    If it still dont work then try to get HttpServletResponse and write your file data to Stream with response.setContentType();

    Note :: Recently I have use response.getOutputStream to write a Excel file. Due to some reasons setting produces wasnt working for me.

    Also you can use Firebug in firefox to see Response headers.

    0 讨论(0)
提交回复
热议问题