赞
踩
vue-upload-component
:npm install vue-upload-component --save
FileUploader.vue
):<template>
<div>
<file-upload
:multiple="false"
:size="5242880"
:thread="1"
:auto="true"
:extensions="['jpg', 'png', 'gif']"
@input-file="inputFile"
ref="upload"
>
<div class="btn btn-primary">选择文件</div>
</file-upload>
</div>
</template>
<script>
import FileUpload from 'vue-upload-component';
export default {
components: {
FileUpload,
},
data() {
return {
uploadUrl: '/upload',
chunkSize: 1 * 1024 * 1024, // 1MB
};
},
methods: {
inputFile(newFile, oldFile, prevent) {
if (newFile && newFile.file) {
if (newFile.active && newFile.size > this.chunkSize) {
prevent();
this.uploadChunks(newFile);
}
}
},
async uploadChunks(file) {
const totalChunks = Math.ceil(file.size / this.chunkSize);
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
const start = chunkIndex * this.chunkSize;
const end = Math.min(start + this.chunkSize, file.size);
const chunk = file.file.slice(start, end);
const formData = new FormData();
formData.append('file', chunk);
formData.append('chunk', chunkIndex + 1);
formData.append('totalChunks', totalChunks);
formData.append('fileName', file.name);
await this.uploadChunk(formData);
}
// Notify backend that all chunks have been uploaded
await this.uploadComplete(file);
},
uploadChunk(formData) {
return fetch(this.uploadUrl, {
method: 'POST',
body: formData,
}).then(response => response.json());
},
uploadComplete(file) {
return fetch(\`\${this.uploadUrl}/complete\`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fileName: file.name,
totalChunks: Math.ceil(file.size / this.chunkSize),
}),
}).then(response => response.json());
},
},
};
</script>
@RestController
@RequestMapping("/upload")
public class FileUploadController {
private final Path rootLocation = Paths.get("upload-dir");
@PostMapping
public ResponseEntity<String> uploadChunk(
@RequestParam("file") MultipartFile file,
@RequestParam("chunk") int chunk,
@RequestParam("totalChunks") int totalChunks,
@RequestParam("fileName") String fileName) throws IOException {
Files.createDirectories(rootLocation);
Path tempFile = this.rootLocation.resolve(fileName + ".part" + chunk);
Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok().body("Chunk " + chunk + " is uploaded successfully.");
}
@PostMapping("/complete")
public ResponseEntity<String> completeUpload(@RequestBody CompleteUploadRequest request) throws IOException {
Path targetFile = this.rootLocation.resolve(request.getFileName());
try (OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
for (int i = 1; i <= request.getTotalChunks(); i++) {
Path tempFile = this.rootLocation.resolve(request.getFileName() + ".part" + i);
Files.copy(Files.newInputStream(tempFile), os);
Files.delete(tempFile);
}
}
return ResponseEntity.ok().body("File uploaded and merged successfully.");
}
public static class CompleteUploadRequest {
private String fileName;
private int totalChunks;
// Getters and setters
}
}
以上代码展示了如何在Vue 3中使用vue-upload-component
实现分片上传,并使用Spring Boot在后端保存文件。前端将文件分片并逐个上传到后端,后端接收到所有分片后再进行合并,最终保存为一个完整文件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。