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

    Element - The world's most popular Vue UI framework

    常用的基本属性:

    参数说明类型可选值默认值
    action必选参数,上传的地址string
    headers设置上传的请求头部object
    multiple是否支持多选文件boolean
    data上传时附带的额外参数object
    name上传的文件字段名stringfile
    with-credentials支持发送 cookie 凭证信息booleanfalse
    show-file-list是否显示已上传文件列表booleantrue
    drag是否启用拖拽上传booleanfalse
    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文件列表的类型stringtext/picture/picture-cardtext
    auto-upload是否在选取文件后立即进行上传booleantrue
    file-list上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]array[]
    http-request覆盖默认的上传行为,可以自定义上传的实现function
    disabled是否禁用booleanfalse
    limit最大允许上传个数number

    二、需要实现的效果:

      通过单击文件上传按钮,能够弹窗一个Dialog文件选择框,通过点击选取文件按钮选择需要导入的Excel文件,然后手动点击数据导入按钮将Excel文件流通过Post请求传输到ASP.NET Core后台服务中,并进行数据保存操作。

    弹出框效果如下图所示:

     三、代码实现:

    前端Vue代码实现:

    注意,清空已上传的文件列表:

    需要ref="upload"和file-list="fileList"这两个属性同时存在,否则即使调用this.$refs.upload.clearFiles();该方法也无效

    Template代码:
    1. <template>
    2. <div>
    3. <el-dialog title="数据导入" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
    4. <el-upload
    5. class="upload-demo"
    6. ref="upload"
    7. :action="actionRequestUrl"
    8. :on-preview="handlePreview"
    9. :on-remove="handleRemove"
    10. :on-success="fileUploadSuccess"
    11. :on-error="fileUploadFail"
    12. :on-change="fileChange"
    13. :file-list="fileList"
    14. :limit="1"
    15. :auto-upload="false"
    16. :headers="headers">
    17. <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    18. <el-button size="small" @click="downloadTemplate">导入模板下载</el-button>
    19. <div slot="tip" class="el-upload__tip">请按照导入模板中的数据格式导入</div>
    20. </el-upload>
    21. <span slot="footer" class="dialog-footer">
    22. <el-button @click="dialogVisible = false">取 消</el-button>
    23. <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
    24. <el-button style="margin-left: 10px;" type="success" @click="submitUpload">数据导入</el-button>
    25. <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
    26. </span>
    27. </el-dialog>
    28. </div>
    29. </template>
    Js中代码:
    1. <script>
    2. data() {
    3. return {
    4. fileList: [], //文件列表
    5. dialogVisible: false,//Dialog显示状态
    6. headers: { "X-Token": jwtToken }//设置上传的请求头部
    7. fileDownloadUrl:'www.xxxx.com',//文件下载地址
    8. actionRequestUrl:'www.xxxx.com/fileUpload'//请求服务器接口地址
    9. }},
    10. //执行相关的方法
    11. methods: {
    12. //打开导入弹窗
    13. openImporDialog() {
    14. this.dialogVisible = true;
    15. },
    16. //关闭弹窗
    17. handleClose() {
    18. this.dialogVisible = false;
    19. },
    20. //上传到服务器
    21. submitUpload() {
    22. console.log(this.fileList);
    23. if (this.fileList.length <= 0) {
    24. this.$message.error("请先选择需要上传的文件!");
    25. return false;
    26. }
    27. this.$refs.upload.submit();
    28. },
    29. //文件上传服务端失败时的钩子
    30. fileUploadFail: function(err, file, fileList) {
    31. console.log("文件上传失败", file, fileList);
    32. },
    33. //文件上传服务端成功时的钩子
    34. fileUploadSuccess: function(response, file, fileList) {
    35. console.log("上传成功");
    36. console.log(response);
    37. //清空已上传的文件列表
    38. this.$refs.upload.clearFiles();
    39. if (response.result) {
    40. this.dialogVisible = false;
    41. this.$message({
    42. message: response.message,
    43. type: "success"
    44. });
    45. } else {
    46. this.$message.error(response.message);
    47. }
    48. },
    49. //文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
    50. fileChange(file, fileList) {
    51. //解决无法判断el-upload是否上传过文件问题
    52. this.fileList = fileList;
    53. console.log("选择文件上传成功后显示的内容》", file, fileList);
    54. },
    55. //文件列表移除文件时的钩子
    56. handleRemove(file, fileList) {
    57. this.fileList = [];
    58. // return this.$confirm(`确定移除 ${file.name}?`);
    59. },
    60. //点击文件列表中已上传的文件时的钩子
    61. handlePreview(file) {
    62. console.log(file);
    63. },
    64. //导入模板下载
    65. downloadTemplate() {
    66. window.location.href =this.fileDownloadUrl+"/xxxExcel导入模板.xlsx";
    67. }
    68. }
    69. </script>

    服务端ASP.NET Core WEB API来进行文件流数据接收和保存:  

    ASP.NET Core单文件和多文件上传并保存到服务端详情概述:

    https://www.cnblogs.com/Can-daydayup/p/12637100.html

    1. using System;
    2. using System.IO;
    3. using Microsoft.AspNetCore.Hosting;
    4. using Microsoft.AspNetCore.Http;
    5. using Microsoft.AspNetCore.Mvc;
    6. namespace FileUploadManage.Controllers
    7. {
    8. /// <summary>
    9. /// 图片,视频,音频,文档等相关文件通用上传服务类
    10. /// </summary>
    11. public class FileUploadController : Controller
    12. {
    13. private static IHostingEnvironment _hostingEnvironment;
    14. public FileUploadController(IHostingEnvironment hostingEnvironment)
    15. {
    16. _hostingEnvironment = hostingEnvironment;
    17. }
    18. /// <summary>
    19. /// Form表单之单文件上传
    20. /// </summary>
    21. /// <param name="formFile">form表单文件流信息</param>
    22. /// <returns></returns>
    23. public JsonResult FormSingleFileUpload(IFormFile formFile)
    24. {
    25. var currentDate = DateTime.Now;
    26. var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("")
    27. try
    28. {
    29. var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";
    30. //创建每日存储文件夹
    31. if (!Directory.Exists(webRootPath + filePath))
    32. {
    33. Directory.CreateDirectory(webRootPath + filePath);
    34. }
    35. if (formFile != null)
    36. {
    37. //文件后缀
    38. var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式,拓展名
    39. //判断文件大小
    40. var fileSize = formFile.Length;
    41. if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
    42. {
    43. return new JsonResult(new { isSuccess = false, resultMsg = "上传的文件不能大于10M" });
    44. }
    45. //保存的文件名称(以名称和保存时间命名)
    46. var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;
    47. //文件保存
    48. using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
    49. {
    50. formFile.CopyTo(fs);
    51. fs.Flush();
    52. }
    53. //完整的文件路径
    54. var completeFilePath = Path.Combine(filePath, saveName);
    55. return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", completeFilePath = completeFilePath });
    56. }
    57. else
    58. {
    59. return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" });
    60. }
    61. }
    62. catch (Exception ex)
    63. {
    64. return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message });
    65. }
    66. }
    67. }
    68. }

  • 相关阅读:
    C++STL---Vector、List所要掌握的基本知识
    【面试】——Java面试重难点剖析
    Spring学习笔记4 Bean的作用域
    基于随机差分变异的改进鲸鱼优化算法-附代码
    1.7 完善自定位ShellCode后门
    Model Inspector—软件模型静态规范检查工具
    linux系统编程 (四) gdb调试与makefile
    阿里云将投入70亿元建国际生态、增设6大海外服务中心
    车载网络安全指南 生产、运行和服务阶段(九)
    mybatis之动态SQL语句&分页查询
  • 原文地址:https://blog.csdn.net/qq_37237487/article/details/138170200