• Asp.net MVC 上传文件


    1.功能预览

     2.前端代码

     <div class="panelContent" id="pagels">
                <form id="formtable" enctype="multipart/form-data">
                    <input type="file" id="files" name="files" multiple class="btn mx-sm-3 btnPrimayBlue" onchange="fileChange(this)" />
                    <input type="button" id="btnok" value="上傳(最多5個,最大2M)" class="btn mx-sm-3 btnPrimayBlue" />
                </form>
            </div>
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        function fileChange(target) {
            var fileSize = 0;
            // var filetypes = [".jpg", ".png", ".rar", ".txt", ".zip", ".doc", ".ppt", ".xls", ".pdf", ".docx", ".xlsx"];
            var filepath = target.value;
            var filemaxsize = 1024 * 2;//2M
            if (filepath) {
                $('#btnok').prop("disabled", false)
                // var isnext = false;
                // var fileend = filepath.substring(filepath.lastIndexOf("."));
                //if (filetypes && filetypes.length > 0) {
                //    for (var i = 0; i < filetypes.length; i++) {
                //        if (filetypes[i] == fileend) {
                //            isnext = true;
                //            break;
                //        }
                //    }
                //}
                //if (!isnext) {
                //    $('#btnok').prop("disabled", true)
                //    alert("不接受此文件类型!");
                //    target.value = "";
                //    return false;
                //}
            } else {
                $('#btnok').prop("disabled", true)
                return false;
            }
            if (isIE && !target.files) {
                var filePath = target.value;
                var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                if (!fileSystem.FileExists(filePath)) {
                    alertError("附件不存在,请重新输入!");
                    return false;
                }
                var file = fileSystem.GetFile(filePath);
                fileSize = file.Size;
            } else {
                fileSize = target.files[0].size;
            }
    
            var size = fileSize / 1024;
            if (size > filemaxsize) {
                $('#btnok').prop("disabled", true)
                alertError("附件大小不能大于" + filemaxsize / 1024 + "M!");
                target.value = "";
                return false;
            }
            if (size <= 0) {
                alertError("附件大小不能为0M!");
                $('#btnok').prop("disabled", true)
                target.value = "";
                return false;
            }
        }
    
    
        function DocFTP() {
            var form = document.getElementById("formtable");
            var formdata = new FormData(form);
            formdata.append("MTNO", MTNO());
            formdata.append("DeptID", DeptID());
            $.ajax({
                url: '@Url.Action("Upload")',
                data: formdata,
                type: 'post',
                datatype: 'json',
                // XMLHttpRequest会对 formdata 进行正确的处理
                processData: false,
                //必须false才会自动加上正确Content-Type
                contentType: false,
                beforeSend: function () {
                    alertError("文檔上傳中......");
                },
                success: function (data) {
                    if (data.Message) {
                        flag = false;
                        alertError(data.Message);
                    }
                    else {
                        alertError("文檔上傳成功!");
                    }
                },
                error: function (data) {
                    if (data.Message) {
                        flag = false;
                        alertError(data.Message);
                    }
                    else { alertError("請重新打開或刷新本頁面後重試!"); }
                },
            })
        }

    3.后端代码

     [HttpPost]
            public ActionResult Upload(HttpPostedFileBase[] files)
            {         
                var fi = files;           
                string mtNO = Request["MTNO"].ToString();
                int deptID = Convert.ToInt32( Request["DeptID"]);
                string docType = "MT"; // Request["DocType"].ToString();
                //string saveFileName = string.Empty;//動態生成 todo 還是用原來的文件名                                               //獲取周
                string strWeek = System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday).ToString();
                string strProName = "EMS_MT_EVIDFILE";
                string fileExtenName = string.Empty;
                string fileName=string.Empty;
                var filePath = @"\IPUploadDoc" + strProName + @"" + PlantID + @"" + DateTime.Now.ToString("yyyy") + strWeek.PadLeft(2, '0') + @"";         
                var filePathBackup = @"\IPUploadDoc" + "EMS_MT_EVIDFILE_BACKUP" + @"" + PlantID + @"" + DateTime.Now.ToString("yyyy") + strWeek.PadLeft(2, '0') + @"";
                #region 創建文件路徑
                if (!Directory.Exists(filePath))
                {
                    try
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    catch (Exception ex)
                    {
    
                    }
                } 
                #endregion
                if (fi != null)
                {
                    try
                    {
                        var virtualPath = string.Empty;
                        //最大seq
                        int maxSeq = mtEvidFileBLL.GetMaxSeqByMTNO(string.Format(" PlantID = '{0}' and MTNO = '{1}' and DocType = '{2}' " ,PlantID,mtNO,docType));                  
                        List<Lib.Model.EMS.Spart.MTEvidFile> fileModeles = new List<Lib.Model.EMS.Spart.MTEvidFile>();
                        foreach (var file in fi)
                        {
                            maxSeq++;
                            int seq = maxSeq;
                            if (seq > 5)
                            { throw new Exception(string.Format("上傳失敗,已上傳{0}個檔案,最多只能上傳5個檔案!",seq-1)); }
                            fileExtenName = System.IO.Path.GetExtension(file.FileName);
                            fileName = string.Format("{0}_{1}{2}",mtNO, seq , fileExtenName);
                            virtualPath = filePath + fileName;
                            Lib.Model.EMS.Spart.MTEvidFile mtFileModel = new Lib.Model.EMS.Spart.MTEvidFile()
                            { MTEvidFileGUID = ResultHelper.NewGuid, DeptID = (int)deptID, DOCType = docType, EmpID=LoginUserID, Enabled = "Y",
                                EvidFileSeq = seq , MTNO = mtNO, OperatorRemark = "", PlantID = PlantID, UpdateTime = ResultHelper.NowTime,
                            ShowFIleName= fileName , SaveFileName= virtualPath
                            };
                            fileModeles.Add(mtFileModel);
                            virtualPath =  filePath + fileName;
                            #region MyRegion
                            //如已有備份則刪除
                            if (System.IO.File.Exists(filePathBackup + fileName))
                            {
                                System.IO.File.Delete(filePathBackup + fileName);
                            }
                            //移動到備份
                            if (System.IO.File.Exists(filePath + fileName))
                            {
                                if (!Directory.Exists(filePathBackup))
                                {
                                    try
                                    {
                                        Directory.CreateDirectory(filePathBackup);
                                    }
                                    catch (Exception ex)
                                    {
    
                                    }
                                }
                                System.IO.File.Move(filePath + fileName, filePathBackup + fileName);
                            } 
                            #endregion
                            // 保存文件
                            file.SaveAs(virtualPath);
                        }
                        //
                        mtEvidFileBLL.Save(fileModeles);
                        return Json(new { Success = true, Filepath = virtualPath, Message = "上傳成功!" });                   
                    }
                    catch (Exception ex)
                    {
                        return Json(new { Success = false, Message = ex.Message });                    
                    }
                }
                else
                { 
                    return Json(new { Success = false, Message = "沒有要上傳的文件!!" });
                }                   
            }

    欢迎转载,转载请注明出处:http://www.cnblogs.com/Tonyyang/

  • 相关阅读:
    springboot 时间戳和 数据库时间相差14个小时
    财富的起源读书笔记1
    高性能mysql读书笔记1
    springboot项目使用 apollo 配置中心
    MongoDB图形化管理工具
    oracle体系结构详解
    三、oracle 体系结构
    用DOS批处理实现FTP自动上传、下载、清理文件
    ORA-01033:ORACLE initialization or shutdown in progress
    从WEB SERVICE 上返回大数据量的DATASET
  • 原文地址:https://www.cnblogs.com/Tonyyang/p/15162512.html
走看看 - 开发者的网上家园