实验- 分片上传 VS 直接上传

分片上传和直接上传是两种常见的文件上传方式。分片上传将文件分成多个小块,每次上传一个小块,可以并行处理多个分片,适用于大文件上传,减少了单个请求的大小,能有效避免因网络波动或上传中断导致的失败,并支持断点续传。相比之下,直接上传是将文件作为一个整体上传,通常适用于较小的文件,简单快捷,但对于大文件来说,容易受到网络环境的影响,上传中断时需要重新上传整个文件。因此,分片上传在大文件上传中具有更高的稳定性和可靠性。

FileUploadController

package per.mjn.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import per.mjn.service.FileUploadService;import java.io.File;
import java.io.IOException;
import java.util.List;@RestController
@RequestMapping("/upload")
public class FileUploadController {private static final String UPLOAD_DIR = "F:/uploads/";@Autowiredprivate FileUploadService fileUploadService;// 启动文件分片上传@PostMapping("/start")public ResponseEntity<String> startUpload(@RequestParam("file") MultipartFile file,@RequestParam("totalParts") int totalParts,@RequestParam("partIndex") int partIndex) {try {String fileName = file.getOriginalFilename();fileUploadService.saveChunk(file, partIndex);  // 存储单个分片return ResponseEntity.ok("Chunk " + partIndex + " uploaded successfully.");} catch (IOException e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading chunk: " + e.getMessage());}}// 多线程并行上传所有分片@PostMapping("/uploadAll")public ResponseEntity<String> uploadAllChunks(@RequestParam("file") List<MultipartFile> files,@RequestParam("fileName") String fileName) {try {fileUploadService.uploadChunksInParallel(files, fileName);  // 调用并行上传方法return ResponseEntity.ok("All chunks uploaded successfully.");} catch (Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading chunks: " + e.getMessage());}}// 合并文件分片@PostMapping("/merge")public ResponseEntity<String> mergeChunks(@RequestParam("fileName") String fileName,@RequestParam("totalParts") int totalParts) {try {System.out.println(fileName);System.out.println(totalParts);fileUploadService.mergeChunks(fileName, totalParts);return ResponseEntity.ok("File uploaded and merged successfully.");} catch (IOException e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error merging chunks: " + e.getMessage());}}// 直接上传整个文件@PostMapping("/file")public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {try {String fileName = file.getOriginalFilename();File targetFile = new File(UPLOAD_DIR + fileName);File dir = new File(UPLOAD_DIR);if (!dir.exists()) {dir.mkdirs();}file.transferTo(targetFile);return ResponseEntity.ok("File uploaded successfully: " + fileName);} catch (IOException e) {return ResponseEntity.status(500).body("Error uploading file: " + e.getMessage());}}
}

FileUploadService

package per.mjn.service;import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.util.List;public interface FileUploadService {public void saveChunk(MultipartFile chunk, int partIndex) throws IOException;public void uploadChunksInParallel(List<MultipartFile> chunks, String fileName);public void mergeChunks(String fileName, int totalParts) throws IOException;
}

FileUploadServiceImpl

package per.mjn.service.impl;import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import per.mjn.service.FileUploadService;import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;@Service
public class FileUploadServiceImpl implements FileUploadService {private static final String UPLOAD_DIR = "F:/uploads/";private final ExecutorService executorService;public FileUploadServiceImpl() {// 使用一个线程池来并发处理上传this.executorService = Executors.newFixedThreadPool(4); // 4个线程用于并行上传}// 保存文件分片public void saveChunk(MultipartFile chunk, int partIndex) throws IOException {File dir = new File(UPLOAD_DIR);if (!dir.exists()) {dir.mkdirs();}File chunkFile = new File(UPLOAD_DIR + chunk.getOriginalFilename() + ".part" + partIndex);chunk.transferTo(chunkFile);}// 处理所有分片的上传public void uploadChunksInParallel(List<MultipartFile> chunks, String fileName) {List<Callable<Void>> tasks = new ArrayList<>();for (int i = 0; i < chunks.size(); i++) {final int index = i;final MultipartFile chunk = chunks.get(i);tasks.add(() -> {try {saveChunk(chunk, index);System.out.println("Uploaded chunk " + index + " of " + fileName);} catch (IOException e) {e.printStackTrace();}return null;});}try {// 执行所有上传任务executorService.invokeAll(tasks);} catch (InterruptedException e) {e.printStackTrace();}}// 合并文件分片public void mergeChunks(String fileName, int totalParts) throws IOException {File mergedFile = new File(UPLOAD_DIR + fileName);try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(mergedFile))) {for (int i = 0; i < totalParts; i++) {File chunkFile = new File(UPLOAD_DIR + fileName + ".part" + i);try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(chunkFile))) {byte[] buffer = new byte[8192];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}chunkFile.delete(); // 删除临时分片文件}}}
}

前端测试界面

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>File Upload</title>
</head>
<body><h1>File Upload</h1><input type="file" id="fileInput"><button onclick="startUpload()">Upload File</button><button onclick="directUpload()">Upload File Directly</button><script>const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB per chunkconst fileInput = document.querySelector('#fileInput');let totalChunks;function startUpload() {const file = fileInput.files[0];totalChunks = Math.ceil(file.size / CHUNK_SIZE);let currentChunk = 0;let files = [];while (currentChunk < totalChunks) {const chunk = file.slice(currentChunk * CHUNK_SIZE, (currentChunk + 1) * CHUNK_SIZE);files.push(chunk);currentChunk++;}// 并行上传所有分片uploadAllChunks(files, file.name);}function uploadAllChunks(chunks, fileName) {const promises = chunks.map((chunk, index) => {const formData = new FormData();formData.append('file', chunk, fileName);formData.append('partIndex', index);formData.append('totalParts', totalChunks);formData.append('fileName', fileName);return fetch('http://172.20.10.2:8080/upload/start', {method: 'POST',body: formData}).then(response => response.text()).then(data => console.log(`Chunk ${index} uploaded successfully.`)).catch(error => console.error(`Error uploading chunk ${index}`, error));});// 等待所有分片上传完成Promise.all(promises).then(() => {console.log('All chunks uploaded, now merging.');mergeChunks(fileName);}).catch(error => console.error('Error during uploading chunks', error));}function mergeChunks(fileName) {fetch(`http://172.20.10.2:8080/upload/merge?fileName=${fileName}&totalParts=${totalChunks}`, {method: 'POST'}).then(response => response.text()).then(data => console.log('File uploaded and merged successfully.')).catch(error => console.error('Error merging chunks', error));}// 直接上传整个文件function directUpload() {const file = fileInput.files[0];if (!file) {alert('Please select a file to upload.');return;}const formData = new FormData();formData.append('file', file); // 将整个文件添加到 FormDatafetch('http://172.20.10.2:8080/upload/file', {method: 'POST',body: formData}).then(response => response.text()).then(data => console.log('File uploaded directly: ', data)).catch(error => console.error('Error uploading file directly', error));}</script>
</body>
</html>

测试分片上传与直接上传耗时

我们上传一个310MB的文件,分片上传每个分片在前端设置为10MB,在后端开5个线程并发执行上传操作。
直接上传没有分片大小也没有开多线程,下面是两种方式的测试结果。
在这里插入图片描述
分片上传,耗时2.419s
在这里插入图片描述

直接上传,耗时4.572s

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/898167.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Android视频渲染SurfaceView强制全屏与原始比例切换

1.创建UI添加强制全屏与播放按钮 2.SurfaceView控件设置全屏显示 3.全屏点击事件处理实现 4.播放点击事件处理 5.使用接口更新强制全屏与原始比例文字 强制全屏/原始比例 点击实现

数据结构——串、数组和广义表

串、数组和广义表 1. 串 1.1 串的定义 串(string)是由零个或多个字符组成的有限序列。一般记为 S a 1 a 2 . . . a n ( n ≥ 0 ) Sa_1a_2...a_n(n\geq0) Sa1​a2​...an​(n≥0) 其中&#xff0c;S是串名&#xff0c;单引号括起来的字符序列是串的值&#xff0c; a i a_i a…

无再暴露源站!群联AI云防护IP隐匿方案+防绕过实战

一、IP隐藏的核心原理 群联AI云防护通过三层架构实现源站IP深度隐藏&#xff1a; 流量入口层&#xff1a;用户访问域名解析至高防CNAME节点&#xff08;如ai-protect.example.com&#xff09;智能调度层&#xff1a;基于AI模型动态分配清洗节点&#xff0c;实时更新节点IP池回…

1.5.3 掌握Scala内建控制结构 - for循环

Scala的for循环功能强大&#xff0c;支持单重和嵌套循环。单重for循环语法为for (变量 <- 集合或数组 (条件)) {语句组}&#xff0c;可选筛选条件&#xff0c;循环变量依次取集合值。支持多种任务&#xff0c;如输出指定范围整数&#xff08;使用Range、to、until&#xff0…

【MySQL基础-9】深入理解MySQL中的聚合函数

在数据库操作中&#xff0c;聚合函数是一类非常重要的函数&#xff0c;它们用于对一组值执行计算并返回单个值。MySQL提供了多种聚合函数&#xff0c;如COUNT、SUM、AVG、MIN和MAX等。这些函数在数据分析和报表生成中扮演着关键角色。本文将深入探讨这些聚合函数的使用方法、注…

windows版本的时序数据库TDengine安装以及可视化工具

了解时序数据库TDengine&#xff0c;可以点击官方文档进行详细查阅 安装步骤 首先找到自己需要下载的版本&#xff0c;这边我暂时只写windows版本的安装 首先我们需要点开官网&#xff0c;找到发布历史&#xff0c;目前TDengine的windows版本只更新到3.0.7.1&#xff0c;我们…

Web测试

7、Web安全测试概述 黑客技术的发展历程 黑客基本涵义是指一个拥有熟练电脑技术的人&#xff0c;但大部分的媒体习惯将“黑客”指作电脑侵入者。 黑客技术的发展 在早期&#xff0c;黑客攻击的目标以系统软件居多。早期互联网Web并非主流应用&#xff0c;而且防火墙技术还没有…

华为OD机试 - 最长的完全交替连续方波信号(Java 2023 B卷 200分)

题目描述 给定一串方波信号,要求找出其中最长的完全连续交替方波信号并输出。如果有多个相同长度的交替方波信号,输出任意一个即可。方波信号的高位用1标识,低位用0标识。 说明: 一个完整的信号一定以0开始并以0结尾,即010是一个完整的信号,但101,1010,0101不是。输入的…

游戏引擎学习第163天

我们可以在资源处理器中使用库 因为我们的资源处理器并不是游戏的一部分&#xff0c;所以它可以使用库。我说过我不介意让它使用库&#xff0c;而我提到这个的原因是&#xff0c;今天我们确实有一个选择——可以使用库。 生成字体位图的两种方式&#xff1a;求助于 Windows 或…

7、什么是死锁,如何避免死锁?【高频】

&#xff08;1&#xff09;什么是死锁&#xff1a; 死锁 是指在两个或多个进程的执行时&#xff0c;每个进程都持有资源 并 等待其他进程 释放 它所需的资源&#xff0c;如果此时所有的进程一直占有资源而不释放&#xff0c;就会陷入互相等待的一种僵局状态。 死锁只有同时满足…

Compose 实践与探索十四 —— 自定义布局

自定义布局在 Compose 中相对于原生的需求已经小了很多&#xff0c;先讲二者在本质上的逻辑&#xff0c;再说它们的使用场景&#xff0c;两相对比就知道为什么 Compose 中的自定义布局的需求较小了。 原生是在 xml 布局文件不太方便或者无法满足需求时才会在代码中通过自定义 …

【C++】:C++11详解 —— 入门基础

目录 C11简介 统一的列表初始化 1.初始化范围扩展 2.禁止窄化转换&#xff08;Narrowing Conversion&#xff09; 3.解决“最令人烦恼的解析”&#xff08;Most Vexing Parse&#xff09; 4.动态数组初始化 5. 直接初始化返回值 总结 声明 1.auto 类型推导 2. declty…

oracle删除表中重复数据

需求&#xff1a; 删除wfd_procs_nodes_rwk表中&#xff0c;huser_id、dnode_id、rwk_name字段值相同的记录&#xff0c;如果有多条&#xff0c;只保留一条。 SQL&#xff1a; DELETE FROM wfd_procs_nodes_rwk t WHERE t.rowid > (SELECT MIN(t1.rowid)FROM wfd_procs_n…

ESP32学习 -从STM32工程架构进阶到ESP32架构

ESP32与STM32项目文件结构对比解析 以下是对你提供的ESP32项目文件结构的详细解释&#xff0c;并与STM32&#xff08;以STM32CubeIDE为例&#xff09;的常见结构进行对比&#xff0c;帮助你理解两者的差异&#xff1a; 1. ESP32项目文件解析 文件/目录作用STM32对应或差异set…

整形在内存中的存储(例题逐个解析)

目录 一.相关知识点 1.截断&#xff1a; 2.整形提升&#xff1a; 3.如何 截断&#xff0c;整型提升&#xff1f; &#xff08;1&#xff09;负数 &#xff08;2&#xff09;正数 &#xff08;3&#xff09;无符号整型&#xff0c;高位补0 注意&#xff1a;提升后得到的…

HTML中滚动加载的实现

设置div的overflow属性&#xff0c;可以使得该div具有滚动效果&#xff0c;下面以div中包含的是table来举例。 当table的元素较多&#xff0c;以至于超出div的显示范围的话&#xff0c;观察下该div元素的以下3个属性&#xff1a; clientHeight是div的显示高度&#xff0c;scrol…

Netty基础—7.Netty实现消息推送服务二

大纲 1.Netty实现HTTP服务器 2.Netty实现WebSocket 3.Netty实现的消息推送系统 (1)基于WebSocket的消息推送系统说明 (2)消息推送系统的PushServer (3)消息推送系统的连接管理封装 (4)消息推送系统的ping-pong探测 (5)消息推送系统的全连接推送 (6)消息推送系统的HTTP…

人工智能助力家庭机器人:从清洁到陪伴的智能转型

引言&#xff1a;家庭机器人进入智能时代 过去&#xff0c;家庭机器人只是简单的“工具”&#xff0c;主要用于扫地、拖地、擦窗等单一任务。然而&#xff0c;随着人工智能&#xff08;AI&#xff09;技术的迅猛发展&#xff0c;家庭机器人正经历从“机械助手”向“智能管家”甚…

ssh转发笔记

工作中又学到了&#xff0c;大脑转不过来 现有主机A&#xff0c;主机B&#xff0c;主机C A能访问B&#xff0c;B能访问C&#xff0c;A不能访问C C上80端口有个服务&#xff0c;现在A想访问这个服务&#xff0c;领导让用ssh转发&#xff0c;研究半天没找到理想的语句&#xf…

清晰易懂的Miniconda安装教程

小白也能看懂的 Miniconda 安装教程 Miniconda 是一个轻量级的 Python 环境管理工具&#xff0c;适合初学者快速搭建 Python 开发环境。本教程将手把手教你如何在 Windows 系统上安装 Miniconda&#xff0c;并配置基础环境&#xff0c;确保你能够顺利使用 Python 进行开发。即…