vue界面和springboot后端分段传文件代码

时间: 2024-03-19 13:45:23 浏览: 11
以下是一个简单的Vue界面和Spring Boot后端分段传输文件的代码示例: Vue界面代码: ``` <template> <div> <input type="file" @change="selectFile"> <button @click="uploadFile">上传文件</button> </div> </template> <script> export default { data() { return { file: null, fileSize: 0, chunkSize: 1024 * 1024, // 每个分段大小为1MB chunks: [], uploadedChunks: [] } }, methods: { selectFile(event) { this.file = event.target.files[0] this.fileSize = this.file.size this.chunks = this.splitFileIntoChunks() this.uploadedChunks = [] }, splitFileIntoChunks() { const chunks = [] let chunkIndex = 0 let offset = 0 while (offset < this.fileSize) { const chunk = this.file.slice(offset, offset + this.chunkSize) chunks.push({ index: chunkIndex, file: chunk, uploaded: false }) offset += this.chunkSize chunkIndex++ } return chunks }, async uploadFile() { for (let i = 0; i < this.chunks.length; i++) { const chunk = this.chunks[i] if (!chunk.uploaded) { await this.uploadChunk(chunk) } } }, uploadChunk(chunk) { return new Promise((resolve, reject) => { const formData = new FormData() formData.append('file', chunk.file) formData.append('index', chunk.index) formData.append('total', this.chunks.length) const xhr = new XMLHttpRequest() xhr.open('POST', 'http://localhost:8080/upload') xhr.setRequestHeader('Content-Type', 'multipart/form-data') xhr.onload = () => { if (xhr.status === 200) { chunk.uploaded = true this.uploadedChunks.push(chunk) resolve() } else { reject() } } xhr.onerror = () => { reject() } xhr.send(formData) }) } } } </script> ``` Spring Boot后端代码: ``` @RestController public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("index") int index, @RequestParam("total") int total) { try { // 检查上传的文件是否为空 if (file.isEmpty()) { return ResponseEntity.badRequest().body("上传的文件不能为空"); } // 创建目录 File uploadDir = new File("upload"); if (!uploadDir.exists()) { uploadDir.mkdir(); } // 保存分段文件 File chunkFile = new File(uploadDir, index + ".part"); file.transferTo(chunkFile); // 检查所有分段文件是否都已上传 if (index == total - 1) { File outputFile = new File(uploadDir, file.getOriginalFilename()); FileOutputStream outputStream = new FileOutputStream(outputFile); for (int i = 0; i < total; i++) { File partFile = new File(uploadDir, i + ".part"); FileInputStream inputStream = new FileInputStream(partFile); IOUtils.copy(inputStream, outputStream); inputStream.close(); partFile.delete(); } outputStream.close(); logger.info("文件 {} 上传成功", file.getOriginalFilename()); } return ResponseEntity.ok().build(); } catch (IOException e) { logger.error("文件上传失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败"); } } } ``` 以上代码仅供参考,具体实现还需要根据您的实际需求进行调整。

相关推荐

最新推荐

recommend-type

vue+springboot图片上传和显示的示例代码

主要介绍了vue+springboot图片上传和显示的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

Springboot vue导出功能实现代码

主要介绍了Springboot vue导出功能实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
recommend-type

springboot整合vue实现上传下载文件

主要为大家详细介绍了springboot整合vue实现上传下载文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

Springboot项目与vue项目整合打包的实现方式

主要介绍了Springboot项目与vue项目整合打包的实现方式,本文通过两种方式给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

解决前后端分离 vue+springboot 跨域 session+cookie失效问题

主要介绍了前后端分离 vue+springboot 跨域 session+cookie失效问题的解决方法,解决过程也很简单 ,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。