<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传</button>
<div v-if="progress">上传进度:{{ progress }}%</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
chunkSize: 1 * 1024 * 1024, // 1MB
progress: 0,
uploadedChunks: 0,
};
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
this.checkUploadedChunks();
},
async checkUploadedChunks() {
if (!this.file) return;
// 请求已上传的分片信息
try {
const response = await axios.get(`/upload/check?fileName=${this.file.name}`);
this.uploadedChunks = response.data.uploadedChunks; // 已上传的分片数
} catch (error) {
console.error('获取已上传分片失败', error);
this.uploadedChunks = 0;
}
},
async uploadFile() {
if (!this.file) return;
const totalChunks = Math.ceil(this.file.size / this.chunkSize);
const uploadPromises = [];
for (let i = this.uploadedChunks; i < totalChunks; i++) {
const start = i * this.chunkSize;
const end = Math.min(start + this.chunkSize, this.file.size);
const chunk = this.file.slice(start, end);
const formData = new FormData();
formData.append('file', chunk);
formData.append('chunkIndex', i);
formData.append('totalChunks', totalChunks);
formData.append('fileName', this.file.name);
uploadPromises.push(
axios.post('/upload', formData, {
onUploadProgress: (progressEvent) => {
const percentage = Math.round((progressEvent.loaded / progressEvent.total) * 100);
this.progress = ((i + percentage / 100) / totalChunks) * 100;
},
})
);
}
await Promise.all(uploadPromises);
alert('文件上传完成!');
},
},
};
</script>
``
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@RestController
@RequestMapping(“/upload”)
public class FileUploadController {
private static final String UPLOAD_DIR = "uploads/";
@GetMapping("/check")
public CheckResponse checkUploadedChunks(@RequestParam("fileName") String fileName) {
File file = new File(UPLOAD_DIR + fileName);
if (file.exists()) {
// 计算已上传的分片数
int chunkSize = 1 * 1024 * 1024; // 1MB
int uploadedChunks = (int) (file.length() / chunkSize);
return new CheckResponse(uploadedChunks);
}
return new CheckResponse(0);
}
@PostMapping
public String uploadChunk(@RequestParam("file") MultipartFile file,
@RequestParam("chunkIndex") int chunkIndex,
@RequestParam("totalChunks") int totalChunks,
@RequestParam("fileName") String fileName) throws IOException {
// 创建文件存储目录
File dir = new File(UPLOAD_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
// 将分片写入临时文件
File tempFile = new File(UPLOAD_DIR + fileName + ".part" + chunkIndex);
try (OutputStream out = new FileOutputStream(tempFile)) {
out.write(file.getBytes());
}
// 检查是否所有分片都已上传
if (chunkIndex == totalChunks - 1) {
mergeFiles(fileName, totalChunks);
}
return "Chunk uploaded successfully!";
}
private void mergeFiles(String fileName, int totalChunks) throws IOException {
File mergedFile = new File(UPLOAD_DIR + fileName);
try (OutputStream out = new FileOutputStream(mergedFile, true)) {
for (int i = 0; i < totalChunks; i++) {
File tempFile = new File(UPLOAD_DIR + fileName + ".part" + i);
if (tempFile.exists()) {
out.write(java.nio.file.Files.readAllBytes(tempFile.toPath()));
tempFile.delete(); // 删除临时文件
}
}
}
}
static class CheckResponse {
private int uploadedChunks;
public CheckResponse(int uploadedChunks) {
this.uploadedChunks = uploadedChunks;
}
public int getUploadedChunks() {
return uploadedChunks;
}
}
}