netcore3.1+vue ElementUI多文件带参数上传

 

 

vue前端代码

前端主要使用了ElementUI的el-uploda插件,除去业务代码需要注意的是使用formdata存储片上传时所需的参数

      <el-upload
        class="upload-demo"
        multiple
        ref="upload"
        action="#"
        accept=".jpg,.tif"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-upload="handleBefore"
        :http-request="handleHttpRequest"
        :on-change="handleChange"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button
          style="margin-left: 10px; margin-right: 20px"
          size="small"
          type="success"
          @click="handleUpload">上传到服务器</el-button>
 </el-upload>

data(){
    fileList: [], // 上传文件列表
}

methods:{
    //上传前回调
      handleBefore: function (file) {
        //  this.picData={
        //    name:file.name,
        //    picType:0
        //  }
      },
      // 覆盖默认的上传行为,可以自定义上传的实现
      handleHttpRequest: function (para) {},
      // 文件列表移除文件时的钩子
      handleRemove: function (file, fileList) {
        // console.log(file, fileList);
      },
      handleChange(file, fileList) {
        this.fileList = fileList;
      },
      //上传到服务器
      handleUpload() {
        if (this.selectPicType !== null && this.fileList.length>0) {
          let _this = this;
//使用formdata添加上传时所带参数 let formData = new FormData(); let data = []; let imageType = true; let selectDocument = this.selectDocumentType=="第一部分" ? 0 : this.selectDocumentType=="第二部分" ? 1 : this.selectDocumentType=="第三部分" ? 2 : ""; if(this.selectPicType == 2 && this.selectDocumentType=='') { this.$message({ type:'error', message: '请选择目录!' }) return; } this.fileList.forEach((item) => { var imgName = new RegExp(/^\d+\.(jpg|tif)$/); if(!(imgName.test(item.name))) { imageType = false; } formData.append("files", item.raw); data.push({ VId: this.fuId, //退役军人个人信息id DId: this.currenttMaterialId, //目录材料id ServerPathId: 1, BackUpPathId: 1, PicName: item.name, picType: this.selectPicType, //上传类型 TextType: selectDocument, //正文中的目录 ReelNumber: this.fuReelNumber, //上传卷号 VName: this.fuVName, //退役军人姓名 ArchivesYear: this.fuarchivesYear //年度 }); }); if(imageType == false) { this.$message({ type: 'error', message: '请选择名称为数字的文件,并且是jpg和tif格式' }) this.fileList = []; return; } else if (imageType == true) { formData.append("params",JSON.stringify( data)); multiFileUpload(formData).then((res) => { this.getCurrentList(); this.$message({ type:"success", message: "上传成功" }) this.catalog = false; this.inputShow = false; this.fileList = []; this.selectPicType = null; this.selectDocumentType = ''; selectDocument = ''; this.currenttMaterialId = null; }); } } else { this.$message({ type:"error", message: "选择文件和要上传图片的类型!" }) } }, // 点击文件列表中已上传的文件时的钩子 handlePreview: function (file) { // console.log(file); } }

 

后端代码

后台使用Request.Form来接收参数,把图片上传的信息存到出数据库

 

        /// <summary>
        ///  多文件上传
        /// </summary>
        /// <param name="formCollection">表单集合值</param>
        /// <returns>服务器存储的文件信息</returns>

        [HttpPost]
        public  JsonResult MultiFileUpload(IFormCollection formCollection)
        {
            var currentDate = DateTime.Now;
            //var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 
            //var webRootPath = _hostingEnvironment.ContentRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") 
            var uploadFileRequestList = new List<UploadFileRequest>();
            var jsondata = Request.Form["params"];
            //var UploadPicDTOs = (List<UploadPicDTO>)JsonConvert.DeserializeObject(jsondata,typeof( List< UploadPicDTO >));
            var UploadPicDTOs = JsonConvert.DeserializeObject<List<UploadPicDTO>>(jsondata);
            var insertPicData = new List<TBase_ImgDetailInfo>();
           
            try
            {
                //FormCollection转化为FormFileCollection
                var files = (FormFileCollection)formCollection.Files;


                if (files.Any())
                {
                    foreach (var file in files)
                    {
                        string filePath = string.Empty;
                        var uploadFileRequest = new UploadFileRequest();
                        var picData = UploadPicDTOs.FirstOrDefault(s => s.PicName == file.FileName);
                        var webRootPath = _tImgServerPathService.QueryById(picData.ServerPathId).Result.ServerPath;

                        if (picData.PicType == 0 || picData.PicType == 1 || picData.PicType == 3)
                            filePath = $"\\{picData.ArchivesYear}\\{picData.ReelNumber}-{picData.VName}\\";
                        else
                            filePath = $"\\{picData.ArchivesYear}\\{picData.ReelNumber}-{picData.VName}\\{picData.TextType + 1}\\";


                        //创建每日存储文件夹
                        if (!Directory.Exists(webRootPath + filePath))
                        {
                            Directory.CreateDirectory(webRootPath + filePath);
                        }

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

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

                        if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                        {
                            continue;
                        }

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

                        //文件保存
                        using (var fs = System.IO.File.Create(fullPath))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }

                        //完整的文件路径
                        var completeFilePath = Path.Combine(filePath, saveName);

                        uploadFileRequestList.Add(new UploadFileRequest()
                        {
                            FileName = saveName,
                            FilePath = completeFilePath
                        });
                        insertPicData.Add(new TBase_ImgDetailInfo()
                        {
                            VId = picData.VId,
                            DId = picData.DId,
                            ServerPathId = picData.ServerPathId,
                            BackUpPathId = picData.BackUpPathId,
                            PicName = picData.PicName,
                            PicRealName=saveName,
                            RelativePath = filePath,
                            //FullPath= fullPath,
                            PicType = picData.PicType,
                            TextType = picData.TextType,
                            ArchivesYear = picData.ArchivesYear,
                            PicPageNo= int.Parse(file.FileName.Substring(0, file.FileName.LastIndexOf('.'))),
                            CreateId = _user.ID,
                            CreateBy = _user.Name
                        });
                    }
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message });
            }

            if (uploadFileRequestList.Any())
            {
                _tImgDetailInfoService.Add(insertPicData);
                return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", filePathArray = uploadFileRequestList });
            }
            else
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "网络打瞌睡了,文件保存失败" });
            }
        }


    /// <summary>
    /// 对文件上传响应模型
    /// </summary>
    public class UploadFileRequest
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; }


        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath { get; set; }
    }

 

原文地址:https://www.cnblogs.com/pengboke/p/14373388.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


el-menu 有个属性 :default-active="curActive"  el-menu-item有个属性:index=“home”这2个属性值对上号就自动定位了data(){ return{ curActive:"home" }; },
基础用法1<el-inputv-model="input1"palcehoder="请输入"></el-input>23varMain={4data(){5return{6input1:''7}8}9}10varCtor=Vue.extend(Main)11newCtor().$mount('#app&#03
 1.安装element-uinpminstallelement-ui-S 2.在main.js中importElementUIfrom'element-ui'import'element-ui/libheme-chalk/index.css'Vue.use(ElementUI)注意index.css的路径不要出错:在node_modules文件夹里node_modules\element-ui\lib\theme-c
layout布局通过基础的24分栏,可进行快速布局基础布局使用单一分栏创建基础的栅格布局,通过span属性指定每栏的大小<el-col:span="8"></el-col>1<el-row>2<el-col:span="8"><divclass="grid-contentbg-purple"></div>&
 今天做一个选择年份的功能,直接调用了ElementUI里面的DatePicker组件,官网上有该组件的用法介绍,讲得很清楚。 我的代码: 官网说明: 奇怪的事情发生了,我明明按照例子写了  value-format="yyyy" 可是获得的值却一直还是Date对象 仔细检查后,我突然发现我的v-model
  that.end 即为结束日期
vueelementUitree懒加载使用详情2018年11月21日11:17:04开心大表哥阅读数:3513 https://blog.csdn.net/a419419/article/details/84315751 背景:vue下使用elementUI文档:http://element-cn.eleme.io/#/zh-CN/componentree#tree-shu-xing-kong-jian需求:只保存二
环境搭建说明:1、全局安装angluar脚手架npminstall-g@angular/cli2、初始化项目(支持scss)ngnew项目名称--style=scss//进入项目cd项目名称运行代码可以是:serve或者npminstall(安装依赖)npmstart(运行)3、安装elementnpm
1、在写埋点监控项目的时候,需求是表格里面的数据后台传递过来为0,但是要求显示的时候为—,在elementUI判断,将prop去掉在下面加上<templateslot-scope="scope"><emplate>里面在写vue的判断,因为通过Scopedslot可以获取到row,column,$index和store(table内容的状态管理)的数据。2、
<el-table-columnprop="pubArea"//表格data中对应的字段column-key="pubArea"//过滤条件变化时根据此key判断是哪个表头的过滤label="报修类型"align="center"width=
1.npminstallbabel-plugin-component-D   然后.babelrc替换plugins 文件就在根目录下  2.组件中英文及自定义中英文importVueI18nfrom'vue-i18n'importenLocalefrom'element-ui/lib/locale/lang/en'importzhLocalefrom'element-ui/lib/locale/lang/zh-C
 <el-treeref="tree":data="menu.treeData":props="menu.defaultProps":filter-node-method="filterNode":expand-on-click-node=&quot
2019独角兽企业重金招聘Python工程师标准>>>使用vue+elementui的tree组件,elementui官网elementui的tree组件问题描述:tree层级过多时左右不可滚动问题解决:修改overflow属性值.el-tree-node>.el-tree-node_children{overflow:visible;} 其他相关链接:css--ov
首先elementUI的导航栏中的选中项的高亮显示时的字体颜色可以在属性中设置,但是高亮时的背景颜色不能设置,所以要自己修改高亮的背景颜色.el-menu-item.is-active{background-color:#00b4aa!important;} 在使用elementUI构建vue项目的时候会遇到页面刷新的时候子路由会保
1.首先创建Vue项目(使用vue-cli进行创建)创建项目文章指导地址: https://blog.csdn.net/assiduous_me/article/details/892086492.ElementUI:一套为开发者、设计师和产品经理准备的基于Vue2.0的桌面端组件库 链接地址:http://element.eleme.io/#/zh-CN3.正式开
使用vue开发项目,用到elementUI,根据官网的写法,我们可以自定义主题来适应我们的项目要求,下面来介绍一下两种方法实现的具体步骤,(可以参考官方文档自定义主题官方文档),先说项目中没有使用scss编写,用主题工具的方法(使用的较多)第一种方法:使用命令行主题工具使用vue-cli安装完项目并引
每页显示的序号都是一样的:<el-table:data="tableData"highlight-current-row@current-change="handleCurrentChange"><el-table-columntype="index"width="50"></el-table-column><el-table>根据
  记录一下自己踩的坑,控制element内的table的某列显示隐藏不能用v-show,而是要用v-if具体网上百度了,看一下v-show和v-if的区别吧猜测:由于el-table-column会生成多行标签元素,根据v-show是不支持template语法的,推断v-show不能显示隐藏多个元素 
样式重置单vue文件中重置全局重置多写一个style不加scrop,可能会影响全局样式待补充table单价数量小计3252?在ElementUI中,我需要获取row内的数据并进行计算,需要用到v-slot<el-table-columnlabel="小计"><templatev-slot="scope">{{scop
工作需要做一个带滑块效果的导航栏,初步想法是用element的导航组件去做,后面摸坑结合各位大佬的博客初步实现效果,话不多说,直接上代码,记录一下爬坑之旅1<template>2<divclass="y-nav">3<el-rowclass="nav">4<el-menu5:default-active="$route.