大文件上传缓慢的一种处理办法

JAVA JS

Posted by gomyck on May 8, 2025

同事反馈业务系统在上传大文件时用时过多, 500M 以上的文件上传需要几十秒(局域网环境)

问题复现

通过观测 F12 以及服务端 log 发现, 耗时分为两阶段:

  • 第一阶段: 客户端 至 服务端 的传输过程
  • 第二阶段: 服务端 至 S3 服务 的传输过程

其中第一阶段相对耗时较多, 在点击上传时一直处于 pending 的状态

问题原因

由于服务端使用 spring 框架, 在接收文件时, 使用的上下文是 multipart/form-data, 这种 MIME 的上下文格式的请求, 服务端处于阻塞 IO 状态, 必须要等待所有分块都接收到之后, 在还原成 file

一是会带来内存溢出的风险

二是阻塞会导致时间浪费, 不能同步的进行下一步传输

解决方案

该用 RAW 形式的原始文件流传输, 服务端使用输入流来接收原始文件, 并同步传输给 S3 服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@CrossOrigin(origins = "*")
@PostMapping("/upload")
public ResponseEntity<String> streamToFile(HttpServletRequest request, @RequestParam("filename") String filename) {
    File targetFile = new File("/Users/haoyang/Downloads/xxx/" + filename);
    try (InputStream inputStream = request.getInputStream();
         OutputStream outputStream = Files.newOutputStream(targetFile.toPath())) {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        outputStream.close();
        return ResponseEntity.ok("文件已保存到本地: " + targetFile.getAbsolutePath());
    } catch (Exception e) {
        return ResponseEntity.status(500).body("上传失败: " + e.getMessage());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>文件上传示例</title>
</head>
<body>
  <h2>上传文件</h2>
  <input type="file" id="fileInput" />
  <button onclick="uploadFile()">上传</button>

  <script>
    function uploadFile() {
      const fileInput = document.getElementById('fileInput');
      const file = fileInput.files[0];
      if (!file) {
        alert("请选择一个文件!");
        return;
      }

      fetch("http://127.0.0.1:8001/upload?filename=" + encodeURIComponent(file.name), {
        method: "POST",
        headers: {
          "Content-Type": file.type
        },
        body: file
      })
      .then(res => res.text())
      .then(msg => alert("上传成功:" + msg))
      .catch(err => alert("上传失败:" + err));
    }
  </script>
</body>
</html>