4

我创建了一个 REST 服务,它将发送大文件,例如 ISO 映像,但目前我出现内存不足错误,下面是我的代码

@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/XXX/XXX/XXX/dummyPath/"+fileName);

    if(result.exists()){
        InputStream inputStream = new FileInputStream("/home/XXX/XXX/XXX/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;

}
4

1 回答 1

3

看起来您需要使用InputStreamResource来一次返回流而不是整个文件。

    包app.controller;

    导入 org.springframework.core.io.InputStreamResource;
    导入 org.springframework.http.HttpHeaders;
    导入 org.springframework.http.HttpStatus;
    导入 org.springframework.http.MediaType;
    导入 org.springframework.http.ResponseEntity;
    导入 org.springframework.web.bind.annotation.RequestMapping;
    导入 org.springframework.web.bind.annotation.RequestMethod;
    导入 org.springframework.web.bind.annotation.RequestParam;

    导入java.io.File;
    导入 java.io.FileInputStream;
    导入 java.io.FileNotFoundException;

    @org.springframework.web.bind.annotation.RestController
    @RequestMapping(path = {"/rest"})
    公共类 RestController {

        @RequestMapping(value = "/getISO", 方法 = RequestMethod.GET, 产生 = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        公共 ResponseEntity getIsoFile(@RequestParam(value="filePath", required = true) String filePath) throws FileNotFoundException {
            文件文件 = 新文件(文件路径);
            FileInputStream inputStream = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentLength((int)file.length());
            返回新的 ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
        }
    }

另请注意,在这种情况下,您应该使用 MediaType.APPLICATION_OCTET_STREAM_VALUE 而不是 application/json 作为生成的类型。

希望这可以帮助。

于 2016-04-20T03:30:09.143 回答