• 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/

  • 相关阅读:
    松软科技web课堂:SQLServer之UCASE() 函数
    松软科技web课堂:SQLServer之HAVING 子句
    SQLServer之GROUP BY语句
    松软科技web课堂:SQLServer之SUM() 函数
    松软科技web课堂:SQLServer之MIN() 函数
    SQLServer之MAX() 函数
    松软科技web课堂:SQLServer之LAST() 函数
    松软科技带你学开发:SQL--FIRST() 函数
    松软科技带你学开发:SQL--COUNT() 函数
    NodeJS初介
  • 原文地址:https://www.cnblogs.com/Tonyyang/p/15162512.html
Copyright © 2020-2023  润新知