惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Troy Hunt's Blog
Latest news
Latest news
Help Net Security
Help Net Security
S
Security Affairs
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tor Project blog
Forbes - Security
Forbes - Security
Google DeepMind News
Google DeepMind News
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Help Net Security
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog
Cyberwarzone
Cyberwarzone
The Last Watchdog
The Last Watchdog
S
Securelist
N
News and Events Feed by Topic
S
Secure Thoughts
F
Fortinet All Blogs
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
M
MIT News - Artificial intelligence
F
Full Disclosure
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Microsoft Security Blog
Microsoft Security Blog
I
InfoQ
P
Privacy International News Feed
L
LangChain Blog
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes

博客园 - Tonyyang

【XAF】如何通过前缀或自定义架构将数据库表与内置系统表分开 Power Shell 7 和5.1 批量给pdf添加页码 [XAF] Declare Conditional Appearance Rules in Code DataTableHelper C# 多任务数据同步 【原】 XAF Localization改用百度翻译 C#百度翻译--亲测试可用 SqlQueryDynamic BOM导入 C#上传到FTP Server FREE OFFER - .NET App Security API (Role-based Access Control) 后台管理框架 Model to Model JSON序列化和反序列化日期时间的处理 Asp.net MVC bootstrap 穿梭框 EXT.NET Combox下拉Grid 转 Refresh Excel Pivot Tables Automatically Using SSIS Script Task SQL Server Integration Services SSIS最佳实践 PowerBI
Asp.net MVC 上传文件
Tonyyang · 2021-08-19 · via 博客园 - Tonyyang

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 = @"\\IP\UploadDoc\" + strProName + @"\" + PlantID + @"\" + DateTime.Now.ToString("yyyy") + strWeek.PadLeft(2, '0') + @"\";         
            var filePathBackup = @"\\IP\UploadDoc\" + "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 = "沒有要上傳的文件!!" });
            }                   
        }