java vue大文件分片上传代码
时间: 2023-08-08 22:09:03 浏览: 135
以下是Java和Vue实现大文件分片上传的示例代码:
Java后端代码:
```java
@RestController
@RequestMapping("/upload")
public class UploadController {
@PostMapping("/file")
public Result uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam("index") int index,
@RequestParam("total") int total) throws IOException {
// 校验和过滤文件
if (file.isEmpty() || index < 0 || index >= total) {
return Result.fail("Invalid request");
}
// 保存文件片段到磁盘上
String fileName = file.getOriginalFilename();
String filePath = "/path/to/upload/dir/" + fileName;
File dest = new File(filePath);
file.transferTo(dest);
// 判断是否所有文件片段都已上传完成
if (index == total - 1) {
// 合并文件片段为完整文件
String mergedFilePath = "/path/to/upload/dir/" + fileName;
for (int i = 0; i < total; i++) {
File part = new File("/path/to/upload/dir/" + fileName + ".part" + i);
FileOutputStream fos = new FileOutputStream(mergedFilePath, true);
FileInputStream fis = new FileInputStream(part);
byte[] buffer = new byte[1024 * 1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
part.delete();
}
// 返回上传成功的消息
return Result.success();
} else {
// 返回继续上传的提示
return Result.info("Continue uploading");
}
}
}
```
Vue前端代码:
```vue
<template>
<div>
<input type="file" @change="selectFile">
<button @click="upload">Upload</button>
<div v-if="progress > 0">{{ progress }}%</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
progress: 0,
uploaded: false
}
},
methods: {
selectFile(event) {
this.file = event.target.files[0];
},
async upload() {
if (!this.file) {
return;
}
const fileSize = this.file.size;
const chunkSize = 1 * 1024 * 1024; // 1MB
const totalChunks = Math.ceil(fileSize / chunkSize);
let index = 0;
let uploadedChunks = [];
while (index < totalChunks) {
const start = index * chunkSize;
const end = Math.min(start + chunkSize, fileSize);
const chunk = this.file.slice(start, end);
const formData = new FormData();
formData.append('file', chunk, this.file.name);
formData.append('index', index);
formData.append('total', totalChunks);
if (uploadedChunks.includes(index)) {
// 如果该文件片段已经上传过,则直接跳过
index++;
continue;
}
const response = await axios.post('/upload/file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
// 显示上传进度
this.progress = Math.round((start + progressEvent.loaded) / fileSize * 100);
}
});
if (response.data.code === 0) {
// 文件上传成功
uploadedChunks.push(index);
if (uploadedChunks.length === totalChunks) {
// 所有文件片段都上传完成
this.progress = 100;
this.uploaded = true;
break;
}
} else if (response.data.code === 1) {
// 需要继续上传下一个文件片段
// do nothing
} else {
// 文件上传失败
alert('Upload failed');
break;
}
index++;
}
if (this.uploaded) {
// 显示上传成功的消息
alert('Upload succeeded');
this.progress = 0;
this.file = null;
this.uploaded = false;
}
}
}
}
</script>
```
这是一个简单的示例代码,实际应用中可能需要根据具体需求进行修改和优化。
阅读全文