之前我們文章 手把手帶大家實現 vue2+Spring Boot2.7 文件上傳功能 將了上傳文件
但如果文件很大 就不太好處理了 按正常情況甚至因為超量而報錯
這里 我弄了個足夠大的文件
我們先搭建 Spring Boot2.7 環境
首先 application.yml 代碼編寫如下
server:port: 80
upload:path: D:/upload/
spring:servlet:multipart:max-file-size: 500MBmax-request-size: 500MB
這里 我們改了他對請求大小的限制 不然 你上次300M左右的東西 系統直接拋異常了
然后 我們將FileUploadController 類代碼更改如下
package com.example.javadom.controller;import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;@RestController
public class FileUploadController {//讀取配置文件中的 upload下的path@Value("${upload.path}")private String uploadPath;@PostMapping("/upload")public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {// 處理上傳邏輯,可以根據需要保存文件到指定目錄// 這里假設保存到D:/upload/目錄下try {String filePath = uploadPath + file.getOriginalFilename();file.transferTo(new File(filePath));// 進行后續處理,比如返回成功消息給前端return ResponseEntity.ok("File uploaded successfully");} catch (IOException e) {e.printStackTrace();// 發生錯誤時,返回錯誤消息給前端return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");}}
}
然后 我們vue代碼 將 App.vue改成這樣
<template><div><input type="file" @change="onFileChange" /><button @click="uploadFile">Upload</button><div v-if="uploadProgress !== null">Upload progress: {{ uploadProgress }}%</div></div>
</template><script>
import axios from 'axios';export default {data() {return {file: null,uploadProgress: null,};},methods: {onFileChange(event) {this.file = event.target.files[0];},uploadFile() {const formData = new FormData();formData.append('file', this.file);axios.post('/upload', formData, {headers: {'Content-Type': 'multipart/form-data',},onUploadProgress: (progressEvent) => {this.uploadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);},}).then((response) => {console.log('Upload successful',response);}).catch((error) => {console.error('Upload failed', error);});},},
};
</script>
然后 我們將項目運行起來
這是我們的vue界面
然后 我們看到 D盤下的upload
還是只有上文的兩個圖片
然后 我們點擊頁面中的 選擇文件
將我們的大文件放進來
然后我們點擊 Upload
我們可以看到 請求還沒返回前 onUploadProgress 就在跑了
axios的onUploadProgress 是一個專門用來監聽文件上傳的事件 有興趣可以自己去了解一下
文件上傳完 進度就會100 請求也返回了
我們看看文件夾
我們打開文件看一下
也是沒有任何問題