Spring - 如何将大型分段文件上传到数据库而不存储在本地文件系统上 [英] Spring - How to stream large multipart file uploads to database without storing on local file system

查看:30
本文介绍了Spring - 如何将大型分段文件上传到数据库而不存储在本地文件系统上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring boot 的默认 MultiPartResolver 接口通过将它们存储在本地文件系统上来处理多部分文件的上传.在进入控制器方法之前,整个分段文件必须完成上传到服务器.

Spring boot's default MultiPartResolver interface handles the uploading of multipart files by storing them on the local file system. Before the controller method is entered, the entire multipart file must finish uploading to the server.

我们将所有上传的文件直接存储到数据库中,并且我们的服务器的磁盘配额非常小,因此如果上传大文件,我们会看到 IOExeption - 磁盘配额超出.

We are storing all of our uploaded files directly to a database and our servers have a very small disk quota, so if a large file is uploaded, we are seeing an IOExeption - Disk quota exceeded.

在 Spring 的 MultiPartResolver 将文件存储在本地文件系统上之前,有没有办法直接从客户端的传入请求中获取流,以便我们可以直接将流传输到我们的数据库?

Is there a way to get the stream directly from the client's incoming request before Spring's MultiPartResolver stores the file on the local filesystem so the we can stream directly to our db?

推荐答案

您可以直接使用 apache,如下所述 https://commons.apache.org/proper/commons-fileupload/streaming.html.

You could use apache directly, as described here https://commons.apache.org/proper/commons-fileupload/streaming.html.

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request) throws IOException, FileUploadException {

        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();
                //...
            }
        }
    }
}

确保禁用 spring 多部分解析机制.

Make sure to disable springs multipart resolving mechanism.

application.yml:

application.yml:

spring:
   http:
      multipart:
         enabled: false

这篇关于Spring - 如何将大型分段文件上传到数据库而不存储在本地文件系统上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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