上传文件整理

,初次写博客,不对之处还请指教

在项目实践中发现在上传文件保存时一般有三种方式

  1. 先保存文件,在保存文档,
  2. 同时保存,但表单数据是保存在数据库中,文件是要上传到服务器,也是有先后操作顺序的
  3. 先保存表单,再上传文件

项目里存在上传文件很常见,我的思路是:在提交表单的时候上传文件,上传成功后返回上传的路径,再将返回的路径和表单一起存到数据库,

function submitForm() {
        if (!$('#form').formValid()) {
            return false;
        }      
        $.ajaxFileUpload({
            type: "post",             
            url: "",                 //文件上传的服务器端请求地址
            secureuri: false,     //是否启用安全提交,一般默认为false就行,不用特殊处理
            fileElementId: "filePicture",        //文件上传控件的id   <input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" οnchange="filePictureChange()" />
            dataType: "json",        //返回值类型,一般设置为json,还支持html\xml\script类型
             //用于post请求提交自定义参数
            success: function (data) {
                $("#Route").val(data);//将返回的路径和表单一起存到数据库
                $.submitForm({
                    url: "”,
                    param: $("#form").formSerialize(),
                    success: function () {                     
                    }
                })
            },
            error: function (data, status, e) {
              //  alert("dd");//服务器响应失败处理函数
            }
        });

 下面是上传文件的方法;route是文件要存放的相对路径。返回值为文件存放目录;原文件名;新文件名;

 /// <summary>
        /// 
        /// </summary>
        /// <param name="route">上传文件路径</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpLoadFile(string route)
        {
            
            string pathForSaving = Server.MapPath(route);
            string files = pathForSaving;
            Thread.Sleep(500);
            if (this.CreateFolderIfNeeded(pathForSaving))
            {
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase uploadFile = Request.Files[file] as HttpPostedFileBase;
                    if (uploadFile != null && uploadFile.ContentLength > 0)
                    {
                        var contentType = System.IO.Path.GetExtension(uploadFile.FileName);                     
                        var id = Guid.NewGuid().ToString()+ contentType;
                        files = files + ";" + uploadFile.FileName + ";" + id;
                        var path = Path.Combine(pathForSaving, id);
                        uploadFile.SaveAs(path);
                    }
                }
            }        
            return Json(files, "text/html", JsonRequestBehavior.AllowGet);
        }


 // 检查是否要创建上传文件夹
          private bool CreateFolderIfNeeded(string path)
           {
              bool result = true;
               if (!Directory.Exists(path))
               {
                   try
                   {
                       Directory.CreateDirectory(path);                  
                   }
                   catch (Exception)
                   {
                       //TODO:处理异常
                       result = false;
                   }
               }
               return result;
         }

 

扩展:根据需要,如果表单上传失败,还可以将之前上传的文件删除:

// 根据路径删除文件
        private bool DeleteFolderIfNeeded(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return true;
            }
            string[] route = path.Split(';');
            List<string> paths = new List<string>();
            for (int i = 1; i < route.Length; i++)
            {
              paths.Add(Path.Combine(route[0], route[i]));
            }
            bool result = true;
            foreach (var p in paths)
            {
                if (System.IO.File.Exists(p))
                {
                    try
                    {
                        System.IO.File.Delete(p);
                    }
                    catch (Exception)
                    {
                        //TODO:处理异常
                        result = false;
                    }
                }
            }
            
            return result;
        }

结论:这样一直在一个函数执行成功后再调用另一个函数,调用的层次如果太多会不会不好?没有测试过,如果哪位大神知道还请解惑

转载于:https://www.cnblogs.com/myvsing/p/9166943.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值