ASP.NET Core WEB API 使用element-ui文件上傳組件el-upload執行手動文件文件,並在文件上傳後清空文件
- 2020 年 4 月 11 日
- 筆記
前言:
從開始學習Vue到使用element-ui-admin已經有將近快兩年的時間了,在之前的開發中使用element-ui上傳組件el-upload都是直接使用文件選取後立即選擇上傳,今天剛好做了一個和之前類似的文件選擇上傳的需求,不過這次是需要手動點擊按鈕把文件上傳到伺服器中進行數據導入,而且最多只能夠選擇一個文件進行上傳,上傳成功後需要對file-list中的文件列表數據進行清空操作,在這裡服務端使用的是ASP.NET Core WEB API來進行文件流數據接收和保存。
一、簡單概述el-upload文件上傳組件:
el-upload組件詳情,查看官方解釋:
常用的基本屬性:
參數 | 說明 | 類型 | 可選值 | 默認值 |
---|---|---|---|---|
action | 必選參數,上傳的地址 | string | — | — |
headers | 設置上傳的請求頭部 | object | — | — |
multiple | 是否支援多選文件 | boolean | — | — |
data | 上傳時附帶的額外參數 | object | — | — |
name | 上傳的文件欄位名 | string | — | file |
with-credentials | 支援發送 cookie 憑證資訊 | boolean | — | false |
show-file-list | 是否顯示已上傳文件列表 | boolean | — | true |
drag | 是否啟用拖拽上傳 | boolean | — | false |
accept | 接受上傳的文件類型(thumbnail-mode 模式下此參數無效) | string | — | — |
on-preview | 點擊文件列表中已上傳的文件時的鉤子 | function(file) | — | — |
on-remove | 文件列表移除文件時的鉤子 | function(file, fileList) | — | — |
on-success | 文件上傳成功時的鉤子 | function(response, file, fileList) | — | — |
on-error | 文件上傳失敗時的鉤子 | function(err, file, fileList) | — | — |
on-progress | 文件上傳時的鉤子 | function(event, file, fileList) | — | — |
on-change | 文件狀態改變時的鉤子,添加文件、上傳成功和上傳失敗時都會被調用 | function(file, fileList) | — | — |
before-upload | 上傳文件之前的鉤子,參數為上傳的文件,若返回 false 或者返回 Promise 且被 reject,則停止上傳。 | function(file) | — | — |
before-remove | 刪除文件之前的鉤子,參數為上傳的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,則停止刪除。 | function(file, fileList) | — | — |
list-type | 文件列表的類型 | string | text/picture/picture-card | text |
auto-upload | 是否在選取文件後立即進行上傳 | boolean | — | true |
file-list | 上傳的文件列表, 例如: [{name: ‘food.jpg’, url: ‘https://xxx.cdn.com/xxx.jpg’}] | array | — | [] |
http-request | 覆蓋默認的上傳行為,可以自定義上傳的實現 | function | — | — |
disabled | 是否禁用 | boolean | — | false |
limit | 最大允許上傳個數 | number | — | — |
二、需要實現的效果:
通過單擊文件上傳按鈕,能夠彈窗一個Dialog文件選擇框,通過點擊選取文件按鈕選擇需要導入的Excel文件,然後手動點擊數據導入按鈕將Excel文件流通過Post請求傳輸到ASP.NET Core後台服務中,並進行數據保存操作。
彈出框效果如下圖所示:
三、程式碼實現:
前端Vue程式碼實現:
注意,清空已上傳的文件列表:
需要ref=”upload”和file-list=”fileList”這兩個屬性同時存在,否則即使調用this.$refs.upload.clearFiles();該方法也無效
Template程式碼:
<template> <div> <el-dialog title="數據導入" :visible.sync="dialogVisible" width="30%" :before-close="handleClose"> <el-upload class="upload-demo" ref="upload" :action="actionRequestUrl" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="fileUploadSuccess" :on-error="fileUploadFail" :on-change="fileChange" :file-list="fileList" :limit="1" :auto-upload="false" :headers="headers"> <el-button slot="trigger" size="small" type="primary">選取文件</el-button> <el-button size="small" @click="downloadTemplate">導入模板下載</el-button> <div slot="tip" class="el-upload__tip">請按照導入模板中的數據格式導入</div> </el-upload> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <!-- <el-button type="primary" @click="dialogVisible = false">確 定</el-button> --> <el-button style="margin-left: 10px;" type="success" @click="submitUpload">數據導入</el-button> <!-- <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div> --> </span> </el-dialog> </div> </template>
Js中程式碼:
<script> data() { return { fileList: [], //文件列表 dialogVisible: false,//Dialog顯示狀態 headers: { "X-Token": jwtToken }//設置上傳的請求頭部 fileDownloadUrl:'www.xxxx.com',//文件下載地址 actionRequestUrl:'www.xxxx.com/fileUpload'//請求伺服器介面地址 }}, //執行相關的方法 methods: { //打開導入彈窗 openImporDialog() { this.dialogVisible = true; }, //關閉彈窗 handleClose() { this.dialogVisible = false; }, //上傳到伺服器 submitUpload() { console.log(this.fileList); if (this.fileList.length <= 0) { this.$message.error("請先選擇需要上傳的文件!"); return false; } this.$refs.upload.submit(); }, //文件上傳服務端失敗時的鉤子 fileUploadFail: function(err, file, fileList) { console.log("文件上傳失敗", file, fileList); }, // 文件上傳服務端成功時的鉤子 fileUploadSuccess: function(response, file, fileList) { console.log("上傳成功"); console.log(response); //清空已上傳的文件列表 this.$refs.upload.clearFiles(); if (response.result) { this.dialogVisible = false; this.$message({ message: response.message, type: "success" }); } else { this.$message.error(response.message); } }, //文件狀態改變時的鉤子,添加文件、上傳成功和上傳失敗時都會被調用 fileChange(file, fileList) { //解決無法判斷el-upload是否上傳過文件問題 this.fileList = fileList; console.log("選擇文件上傳成功後顯示的內容》", file, fileList); }, //文件列表移除文件時的鉤子 handleRemove(file, fileList) { this.fileList = []; // return this.$confirm(`確定移除 ${file.name}?`); },
//點擊文件列表中已上傳的文件時的鉤子 handlePreview(file) { console.log(file); }, //導入模板下載 downloadTemplate() { window.location.href =this.fileDownloadUrl+"/xxxExcel導入模板.xlsx"; } } </script>
服務端ASP.NET Core WEB API來進行文件流數據接收和保存:
using System; using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FileUploadManage.Controllers { /// <summary> /// 圖片,影片,音頻,文檔等相關文件通用上傳服務類 /// </summary> public class FileUploadController : Controller { private static IHostingEnvironment _hostingEnvironment; public FileUploadController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } /// <summary> /// Form表單之單文件上傳 /// </summary> /// <param name="formFile">form表單文件流資訊</param> /// <returns></returns> public JsonResult FormSingleFileUpload(IFormFile formFile) { var currentDate = DateTime.Now; var webRootPath = _hostingEnvironment.WebRootPath;//>>>相當於HttpContext.Current.Server.MapPath("") try { var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/"; //創建每日存儲文件夾 if (!Directory.Exists(webRootPath + filePath)) { Directory.CreateDirectory(webRootPath + filePath); } if (formFile != null) { //文件後綴 var fileExtension = Path.GetExtension(formFile.FileName);//獲取文件格式,拓展名 //判斷文件大小 var fileSize = formFile.Length; if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b) { return new JsonResult(new { isSuccess = false, resultMsg = "上傳的文件不能大於10M" }); } //保存的文件名稱(以名稱和保存時間命名) var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension; //文件保存 using (var fs = System.IO.File.Create(webRootPath + filePath + saveName)) { formFile.CopyTo(fs); fs.Flush(); } //完整的文件路徑 var completeFilePath = Path.Combine(filePath, saveName); return new JsonResult(new { isSuccess = true, returnMsg = "上傳成功", completeFilePath = completeFilePath }); } else { return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,未檢測上傳的文件資訊~" }); } } catch (Exception ex) { return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失敗,異常資訊為:" + ex.Message }); } } } }