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组件详情,查看官方解释:

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来进行文件流数据接收和保存:  

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