Asp.Net或WebAPI獲取表單數據流(批量文件上傳)


//Web或WebAPI獲取表單數據流(批量文件上傳)
        public JsonResult UploadFile()
        {
            //HttpPostedFileBase fileBase = Request.Files["fileToUploadKeyID"];
            HttpPostedFileBase fileBase = Request.Files[0]; //獲取客戶端上載的文件的集合

            string resultUrl = string.Empty;//相對文件路徑
            string errMsg = string.Empty;

            if (fileBase == null || fileBase.ContentLength == 0)
            {
                errMsg = "文件為空";
            }
            else
            {
                int MaxSize = 1024 * 1024 * 4;
                if (fileBase.InputStream.Length > MaxSize)
                {
                    errMsg = "文件過大";
                }
                else
                {
                    try
                    {
                        //循環遍歷批量上傳的文件
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            fileBase = Request.Files[i];
                            var Name = System.IO.Path.GetFileName(fileBase.FileName);
                            var fileName = "/upload/" + DateTime.Now.ToString("yyMMddHHmmssffff") + "." + Name.Split('.')[1];
                            var filePath = System.Web.HttpContext.Current.Server.MapPath(fileName);
                            fileBase.SaveAs(filePath);//保存文件

                            resultUrl += fileName + ";";//拼接文件相對路徑
                        }
                    }
                    catch
                    {
                        errMsg = "上傳失敗";
                    }

                }
            }
            return Json(new { errMsg = errMsg, resultUrl = resultUrl.Trim(';') });
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM