Spring MVC:大文件下载,OutOfMemoryException [英] Spring MVC : large files for download, OutOfMemoryException

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

问题描述

如何通过弹簧控制器提供大型文件下载?我稍后讨论了类似的主题:

How to provide large files for download through spring controller ? I followed few discussions on similar topic :

从弹簧控制器下载文件

但是这些解决方案对于大型文件大小为300mb - 600mb。
我在最后一行得到OutOfMemoryException:

but those solutions fails for large files ~ 300mb - 600mb. I am getting OutOfMemoryException on the last line :

@RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getFile(@PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
.
.       
InputStream is = new FileInputStream(resultFile);

response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
.
.         
return IOUtils.toByteArray(is);

我的(naive)假设是IOUtils将处理甚至大文件,但这并不明显。有没有办法如何将文件分割成块,因为下载正在进行中?文件大概在300 - 600mb左右。最大并发下载数量估计为10.

My (naive) assumption was that IOUtils will handle even large files but this is not obviously happening. Is there any way how to split file into chunks as download is in progress ? Files are usually around 300 - 600mb large. Max number of concurrent downloads is estimated to 10.

简单的方法是将文件作为静态内容链接到webserver目录中,但是我们想尝试在Spring应用程序

Easy way would be to link files as static content in the webserver directory but we would like to try do it in within our Spring app.

推荐答案

这是因为您正在将整个文件读入内存,而是使用缓冲的读取和写入。 p>

It is because you are reading the entire file into memory, use a buffered read and write instead.

@RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(@PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {


    InputStream is = new FileInputStream(resultFile);

    response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");


    int read=0;
    byte[] bytes = new byte[BYTES_DOWNLOAD];
    OutputStream os = response.getOutputStream();

    while((read = is.read(bytes))!= -1){
        os.write(bytes, 0, read);
    }
    os.flush();
    os.close(); 
}

这篇关于Spring MVC:大文件下载,OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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