天天看點

ASP.NET Core WEB API 使用element-ui檔案上傳元件el-upload執行手動檔案檔案,并在檔案上傳後清空檔案

前言:

  從開始學習Vue到使用element-ui-admin已經有将近快兩年的時間了,在之前的開發中使用element-ui上傳元件el-upload都是直接使用檔案選取後立即選擇上傳,今天剛好做了一個和之前類似的檔案選擇上傳的需求,不過這次是需要手動點選按鈕把檔案上傳到伺服器中進行資料導入,而且最多隻能夠選擇一個檔案進行上傳,上傳成功後需要對file-list中的檔案清單資料進行清空操作,在這裡服務端使用的是ASP.NET Core WEB API來進行檔案流資料接收和儲存。

一、簡單概述el-upload檔案上傳元件:

el-upload元件詳情,檢視官方解釋:

https://element.eleme.cn/#/zh-CN/component/upload

常用的基本屬性:

參數 說明 類型 可選值 預設值
action 必選參數,上傳的位址 string
headers 設定上傳的請求頭部 object
multiple 是否支援多選檔案 boolean
data 上傳時附帶的額外參數
name 上傳的檔案字段名 file
with-credentials 支援發送 cookie 憑證資訊 false
show-file-list 是否顯示已上傳檔案清單 true
drag 是否啟用拖拽上傳
accept 接受上傳的檔案類型(thumbnail-mode 模式下此參數無效)
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 檔案狀态改變時的鈎子,添加檔案、上傳成功和上傳失敗時都會被調用
before-upload 上傳檔案之前的鈎子,參數為上傳的檔案,若傳回 false 或者傳回 Promise 且被 reject,則停止上傳。
before-remove 删除檔案之前的鈎子,參數為上傳的檔案和檔案清單,若傳回 false 或者傳回 Promise 且被 reject,則停止删除。
list-type 檔案清單的類型 text/picture/picture-card text
auto-upload 是否在選取檔案後立即進行上傳
file-list 上傳的檔案清單, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] array []
http-request 覆寫預設的上傳行為,可以自定義上傳的實作 function
disabled 是否禁用
limit 最大允許上傳個數 number

二、需要實作的效果:

  通過單擊檔案上傳按鈕,能夠彈窗一個Dialog檔案選擇框,通過點選選取檔案按鈕選擇需要導入的Excel檔案,然後手動點選資料導入按鈕将Excel檔案流通過Post請求傳輸到ASP.NET Core背景服務中,并進行資料儲存操作。

彈出框效果如下圖所示:

ASP.NET Core WEB API 使用element-ui檔案上傳元件el-upload執行手動檔案檔案,并在檔案上傳後清空檔案

 三、代碼實作:

前端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來進行檔案流資料接收和儲存:  

ASP.NET Core單檔案和多檔案上傳并儲存到服務端詳情概述:

https://www.cnblogs.com/Can-daydayup/p/12637100.html
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 });
            }

        }
    }
}      

作者:追逐時光者

作者簡介:一個熱愛程式設計,善于分享,喜歡學習、探索、嘗試新事物,新技術的程式猿。

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。如果該篇文章對您有幫助的話,可以點一下右下角的【♥推薦♥】,希望能夠持續的為大家帶來好的技術文章,文中可能存在描述不正确或錯誤的地方,歡迎指正、補充,不勝感激 !

繼續閱讀