使用Java REST发送大型文件(如ISO文件)

3

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

}

文件的大小是多少? - Roman C
2
你可以避免一次性将整个文件读入内存:https://dev59.com/_XDYa4cB1Zd3GeqPA36B - approxiblue
@approxiblue 是的,这篇文章有所帮助,但是对于要发送的大文件,我们定义要下载的字节数,那么理想的字节数是多少呢?因为这个文件大小在700到900 MB之间。 - arpit joshi
1个回答

3
看起来你需要使用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); // 创建Http头信息对象 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength((int)file.length()); // 返回响应实体 return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK); } }
此外,请注意,在这种情况下,您应该使用MediaType.APPLICATION_OCTET_STREAM_VALUE而不是application/json作为生成类型。
希望这可以帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接