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

 

上一篇:java 中读取某个文件夹下所有文件


下一篇:[Vue warn]: Error in callback for watcher "fileList": "TypeError: Cannot create prope