前段時間在使用APS.NET MVC+LayUI作視頻上傳功能的時,發現當上傳一些內存比較大的視頻就會提示上傳失敗,後來經過查閱相關資料發現.NET MVC框架爲考慮安全問題,在運行時對請求的文件的長度(大小)作了限制默認爲4MB(4096KB),所以咱們須要在Web.Config中設置最大請求文件長度大小,本篇博客主要講解如何設置Web.Config中的最大請求文件大小配置和提供一個完整的ASP.NET MVC+LayUI上傳視頻的教程,而且會提供一個完整的示例(是上傳到GitHub)有興趣的能夠耐心的往下看。javascript
由上圖咱們能夠清楚的知道由於咱們所上傳的視頻內容藏毒超過了配置的值,因此上傳失敗了,而且還告訴咱們須要到web.config文件中配置容許最大上傳的文件長度。html
首先咱們打開web.config=>找到system.web=>在httpRuntime中添加maxRequestLength屬性值前端
<system.web> <compilation debug="true" targetFramework="4.7.2"/> <!--maxRequestLength:指示 ASP.NET 支持的最大文件上傳大小。該限制可用於防止用戶將大量未知的文件上傳到服務器致使不安全問題的發生。指定的大小以 KB 爲單位。默認值爲 4096 KB (4 MB)。--> <!--executionTimeout:表示容許執行請求的最大時間限制,單位爲秒。--> <!--這裏設置最大上傳長度未200MB,執行超時時間爲600s--> <httpRuntime targetFramework="4.7.2" maxRequestLength="204800" executionTimeout="600"/> </system.web>
executionTimeout:表示容許執行請求的最大時間限制,單位爲秒。 maxRequestLength:指示 ASP.NET 支持的最大文件上載大小。該限制可用於防止因用戶將大量文件傳遞到該服務器而致使的拒絕服務攻擊。指定的大小以 KB 爲單位。默認值爲 4096 KB (4 MB)。 useFullyQualifiedRedirectUrl:表示指示客戶端重定向是不是徹底限定的(採用 "http://server/path" 格式,這是某些移動控件所必需的),或者指示是否代之以將相對重定向發送到客戶端。若是爲 True,則全部不是徹底限定的重定向都將自動轉換爲徹底限定的格式。false 是默認選項。 minFreeThreads:表示指定容許執行新請求的自由線程的最小數目。ASP.NET 爲要求附加線程來完成其處理的請求而使指定數目的線程保持自由狀態。默認值爲 8。 minLocalRequestFreeThreads:表示ASP.NET 保持的容許執行新本地請求的自由線程的最小數目。該線程數目是爲從本地主機傳入的請求而保留的,以防某些請求在其處理期間發出對本地主機的子請求。這避免了可能的因遞歸從新進入 Web 服務器而致使的死鎖。 appRequestQueueLimit:表示ASP.NET 將爲應用程序排隊的請求的最大數目。當沒有足夠的自由線程來處理請求時,將對請求進行排隊。當隊列超出了該設置中指定的限制時,將經過「503 - 服務器太忙」錯誤信息拒絕傳入的請求。 enableVersionHeader:表示指定 ASP.NET 是否應輸出版本標頭。Microsoft Visual Studio 2005 使用該屬性來肯定當前使用的 ASP.NET 版本。對於生產環境,該屬性不是必需的,能夠禁用。
<link href="~/Content/layer-v3.1.1/layer/theme/default/layer.css" rel="stylesheet" /> <link href="~/Content/layui-v2.4.5/css/layui.css" rel="stylesheet" /> <div class="jumbotron" style="margin-top: 200px;"> <h3><a href="https://www.cnblogs.com/Can-daydayup/">追逐時光者的ASP.NET MVC+LayUI視頻上傳教程</a></h3> <div class="row" style="margin-top: 20px;"> <div class="form-group znStyle"> <label class="col-sm-2 control-label"><em class="zent-form__required">*</em>視頻上傳:</label> <div class="col-sm-6"> <div id="upload_all_file"> <div class="layui-upload"> <button type="button" class="layui-btn" id="VideoBtn"><i class="layui-icon"></i>上傳視頻</button> <input type="hidden" name="Video" id="Video" /> <div class="layui-upload-list" id="videoPlay"> </div> </div> </div> </div> </div> </div> </div> <script src="~/Content/layer-v3.1.1/layer/layer.js"></script> <script src="~/Content/layui-v2.4.5/layui.js"></script> <!--layer.js視頻上傳--> <script type="text/javascript"> var upload; //上傳圖片 layui.use('upload', function () { upload = layui.upload; upload.render({ before: function () { layer.msg('視頻努力上傳中,請耐心等待...', { icon: 16, shade: 0.8, time: false }); }, elem: '#VideoBtn' , url: '@Url.Action("FileLoad","FileUpload")' , accept: 'video' //視頻 , exts: 'mp4'//只容許上傳的後綴(mp4文件) , done: function (res) { console.log(res); layer.closeAll(); layer.msg(res.msg); if (res.code == 1) { $("#Video").val(res.path); $("#videoPlay").html('<video controls="controls" id="currentVideo" style="width:400px;"><source src="' + res.path + '" type="video/mp4" /></video>'); $("#videoPlay").show(); // 自動播放 $("#currentVideo")[0].play(); } } }); $(".layui-upload-list").on("click", "i", function () { $(this).parent().remove(); }); }); </script>
/** * Authority:追追時光者 * CreateTime:2020.08.01 * Description:文件,圖片,視頻,音頻統一上傳接口 */ using System; using System.IO; using System.Text; using System.Web; using System.Web.Mvc; namespace VideoUpload.Controllers { /// <summary> /// 文件,圖片,視頻,音頻統一上傳服務 /// </summary> public class FileUploadController : Controller { /// <summary> /// 對驗證和處理 HTML 窗體中的輸入數據所需的信息進行封裝,如FromData拼接而成的文件[圖片,視頻,文檔等文件上傳] /// </summary> /// <param name="context">FemContext對驗證和處理html窗體中輸入的數據進行封裝</param> /// <returns></returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult FileLoad(FormContext context)//FemContext對驗證和處理html窗體中輸入的數據進行封裝 { HttpPostedFileBase httpPostedFileBase = Request.Files[0];//獲取文件流 if (httpPostedFileBase != null) { try { ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8"); ControllerContext.HttpContext.Response.Charset = "UTF-8"; string fileName = Path.GetFileName(httpPostedFileBase.FileName);//原始文件名稱 string fileExtension = Path.GetExtension(fileName);//文件擴展名 byte[] fileData = ReadFileBytes(httpPostedFileBase);//文件流轉化爲二進制字節 string result = SaveFile(fileExtension, fileData);//文件保存 return string.IsNullOrEmpty(result) ? Json(new { code = 0, path = "", msg = "網絡異常,文件上傳失敗~" }) : Json(new { code = 1, path = result, msg = "文件上傳成功" }); } catch (Exception ex) { return Json(new { code = 0, msg = ex.Message, path = "" }); } } else { return Json(new { code = 0, path = "", msg = "網絡異常,文件上傳失敗~" }); } } /// <summary> /// 將文件流轉化爲二進制字節 /// </summary> /// <param name="fileData">圖片文件流</param> /// <returns></returns> private byte[] ReadFileBytes(HttpPostedFileBase fileData) { byte[] data; using (var inputStream = fileData.InputStream) { if (!(inputStream is MemoryStream memoryStream)) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); } return data; } /// <summary> /// 保存文件 /// </summary> /// <param name="fileExtension">文件擴展名</param> /// <param name="fileData">圖片二進制文件信息</param> /// <returns></returns> private string SaveFile(string fileExtension, byte[] fileData) { string result; string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名稱 string basePath = "UploadFile"; string saveDir = DateTime.Now.ToString("yyyy-MM-dd"); // 文件上傳後的保存路徑 string serverDir = Path.Combine(Server.MapPath("~/"), basePath, saveDir); string fileNme = Path.Combine(serverDir, saveName);//保存文件完整路徑 try { var savePath = Path.Combine(saveDir, saveName); //項目中是否存在文件夾,不存在建立 if (!Directory.Exists(serverDir)) { Directory.CreateDirectory(serverDir); } System.IO.File.WriteAllBytes(fileNme, fileData);//WriteAllBytes建立一個新的文件,按照對應的文件流寫入,假如已存在則覆蓋 //返回前端項目文件地址 result = "/" + basePath + "/" + saveDir + "/" + saveName; } catch (Exception ex) { result = "發生錯誤" + ex.Message; } return result; } } }