1. 程式人生 > >ASP.NET Core WEB API 使用element-ui檔案上傳元件el-upload執行手動檔案檔案,並在檔案上傳後清空檔案

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 上傳時附帶的額外引數 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來進行檔案流資料接收和儲存:  

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 });
            }

        }
    }
}