我的世界做壁纸网站,荥阳网站建设价格,深圳宝安区最新通告,网站邮箱建设之前我们文章 手把手带大家实现 vue2Spring Boot2.7 文件上传功能 将了上传文件 但如果文件很大 就不太好处理了 按正常情况甚至因为超量而报错
这里 我弄了个足够大的文件 我们先搭建 Spring Boot2.7 环境 首先 application.yml 代码编写如下
server:port: 80
upload:path:…之前我们文章 手把手带大家实现 vue2Spring 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下的pathValue(${upload.path})private String uploadPath;PostMapping(/upload)public ResponseEntityString 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改成这样
templatedivinput typefile changeonFileChange /button clickuploadFileUpload/buttondiv v-ifuploadProgress ! nullUpload progress: {{ uploadProgress }}%/div/div
/templatescript
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 请求也返回了 我们看看文件夹 我们打开文件看一下 也是没有任何问题