我是靠谱客的博主 无辜康乃馨,最近开发中收集的这篇文章主要介绍.net core api+element ui el-upload,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

后台

using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RestSharp;

namespace FileUploadManage.Controllers
{
    /// <summary>
    /// 图片,视频,音频,文档等相关文件通用上传服务类
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "yw")]
    public class UploadFileController : Controller
    {
        private static IHostingEnvironment _hostingEnvironment;

        public UploadFileController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// Form表单之单文件上传
        /// </summary>
        /// <param name="file">form表单文件流信息</param>
        /// <returns></returns>
        [HttpPost("/[controller]/FormSingleFileUpload")]
        public JsonResult FormSingleFileUpload(IFormFile file)
        {
            var currentDate = DateTime.Now;
            var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 

            try
            {
                //var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";
                var filePath = $"G:/vuedonet/zipicture/evaluate/{currentDate:yyyyMMdd}/";
                //创建每日存储文件夹
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }

                if (file != null)
                {
                    //文件后缀
                    var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名

                    //判断文件大小
                    /*var fileSize = formFile.Length;

                    if (fileSize > 1024 * 1024 * 100) //10M TODO:(1mb=1024X1024b)
                    {
                        return new JsonResult(new { isSuccess = false, resultMsg = "上传的文件不能大于10M" });
                    }*/

                    //保存的文件名称(以名称和保存时间命名)
                    var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        file.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 });
            }

        }
    }
}

vue组件

<template>
  <div>
    <el-button type="primary" @click="dialogVisible = true">添加</el-button>
    <el-dialog title="数据导入" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-upload
        ref="upload"
        class="upload-demo"
        :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"
      >
        <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>

<script>
  export default {
    data() {
      return {
        fileList: [], //文件列表
        dialogVisible: false, //Dialog显示状态
        //fileDownloadUrl: 'www.xxxx.com', //文件下载地址
        actionRequestUrl: 'http://10.1.6.29:59535/UploadFile/FormSingleFileUpload', //请求服务器接口地址
      }
    },
    methods: {
      //打开导入弹窗
      openImporDialog() {
        this.dialogVisible = true
      },
      //关闭弹窗
      handleClose() {
        this.dialogVisible = false
      },
      //上传到服务器
      submitUpload() {
        console.log('上传服务器')
        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)
        console.log(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>

<style lang="scss" scoped></style>

最后

以上就是无辜康乃馨为你收集整理的.net core api+element ui el-upload的全部内容,希望文章能够帮你解决.net core api+element ui el-upload所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(30)

评论列表共有 0 条评论

立即
投稿
返回
顶部