官網地址:https://element.eleme.cn/#/zh-CN/component/upload
HTML
<el-upload ref="upload" :limit="1" accept=".bin"//接收的文件類型 :action="upload.url"//上傳地址,data中獲取 :headers="upload.headers" :file-list="upload.fileList" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="true"//自動上傳
> <el-button slot="trigger" size="small" type="primary">選取文件</el-button> <div slot="tip" class="el-upload__tip">只能上傳bin文件</div> </el-upload>
JS中添加
//data中添加 // 上傳參數 upload: { // 是否禁用上傳 isUploading: false, // 設置上傳的請求頭部 headers: { Authorization: "Bearer " + getToken() }, // 上傳的地址 url: '/upgradefile/uploadFile',//訪問后台的路徑 // 上傳的文件列表 fileList: [] }, //方法中添加 this.upload.fileList = []; // 文件提交處理 submitUpload() { this.$refs.upload.submit(); }, // 文件上傳中處理 handleFileUploadProgress(event, file, fileList) { this.upload.isUploading = true; }, // 文件上傳成功處理 handleFileSuccess(response, file, fileList) { if(response.code==200){ this.upload.isUploading = false; this.form.filePath = response.msg;//獲取文件路徑,這個地方我把文件存儲的路徑回傳在msg中,填充前台頁面 } else{ this.msgError(response.msg) } }
Controller中獲取並保存到本地
/** * 文件上傳 * @param file * @return 保存路徑 * @throws IOException */ @PostMapping("/uploadFile") public AjaxResult uploadFile(MultipartFile file) throws IOException { String filePath= "E:/temp"; String filePath1 = FileUploadUtils.upload(filePath,file);//文件保存方法 return AjaxResult.success(filePath1); }
效果:如下圖,選取文件后自動上傳,然后返回文件存儲路徑填充前台頁面,之后進行其他處理。