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

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

问题描述

如何通过spring控制器提供大文件下载?我关注了一些关于类似主题的讨论:

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);

我(天真)的假设是 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.

推荐答案

这是因为您正在将整个文件读入内存,请改用缓冲读写.

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天全站免登陆