The ASP.NET Core WEB API uses the element-ui file upload component el-upload to execute manual file files and clear the files after file upload

Foreword:

  It has been almost two years since I started learning Vue to use element-ui-admin. In the previous development, the element-ui upload component el-upload was directly used to select the file immediately after file selection. I just did it today. A file uploading requirement similar to the previous one, but this time it is necessary to manually click the button to upload the file to the server for data import, and at most only one file can be selected for uploading. After the upload is successful, the files in the file-list need to be uploaded The list data is cleared. Here, the server uses the ASP.NET Core WEB API to receive and save the file stream data.

1. A brief overview of the el-upload file upload component:

For details of el-upload components, check the official explanation:

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

Commonly used basic attributes:

parameter Explanation Types of Optional value Defaults
action Required parameters, upload address string
headers Set the upload request header object
multiple Whether to support multi-select files boolean
data Additional parameters attached to upload object
name Uploaded file field name string file
with-credentials Support sending cookie credentials boolean false
show-file-list Whether to display the list of uploaded files boolean true
drag Whether to enable drag and drop upload boolean false
accept Accept the type of uploaded file (this parameter is invalid in thumbnail-mode mode) string
on-preview Hook when clicking on the uploaded file in the file list function(file)
on-remove File list hooks when removing files function(file, fileList)
on-success Hook when the file is uploaded successfully function(response, file, fileList)
on-error Hook when file upload fails function(err, file, fileList)
on-progress Hook when uploading files function(event, file, fileList)
on-change The hook when the file status changes, it will be called when the file is added, the upload is successful and the upload fails function(file, fileList)
before-upload The hook before uploading the file. The parameter is the uploaded file. If false or Promise is returned and rejected, the upload is stopped. function(file)
before-remove The hook before deleting the file. The parameter is the uploaded file and file list. If it returns false or returns to Promise and is rejected, the deletion will stop. function(file, fileList)
list-type Type of file list string text/picture/picture-card text
Auto-upload Whether to upload immediately after selecting the file boolean true
file-list List of uploaded files, for example: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] array []
http-request Override the default upload behavior, you can customize the implementation of upload function
disabled Whether to disable boolean false
limit Maximum number of uploads allowed number

Second, the effect to be achieved:

  By clicking the file upload button, you can pop up a Dialog file selection box, click the select file button to select the Excel file to be imported, and then manually click the data import button to transfer the Excel file stream to the ASP.NET Core background service through a Post request , And save the data.

The effect of the pop-up box is shown below:

 Three, code implementation:

Front-end Vue code implementation:

Note, clear the list of uploaded files:

The two attributes of ref = "upload" and file-list = "fileList" need to exist at the same time, otherwise this method will not work even if this. $ Refs.upload.clearFiles () is called

Template code:

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

        }
    }
}

Guess you like

Origin www.cnblogs.com/Can-daydayup/p/12676870.html
Recommended