通过Java REST发送ISO等大文件

我创建一个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;

}

最佳答案 看起来您需要使用
InputStreamResource一次性返回流而不是整个文件.


    package app.controller;

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

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;

    @org.springframework.web.bind.annotation.RestController
    @RequestMapping(path = {"/rest"})
    public class RestController {

        @RequestMapping(value = "/getISO", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        public ResponseEntity getIsoFile(@RequestParam(value="filePath", required = true) String filePath) throws FileNotFoundException {
            File file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentLength((int)file.length());
            return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
        }
    }

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

希望这可以帮助.

点赞