版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!
恰饭广告
前端:
引用以下两个js文件
<script type="text/javascript" src="https://www.idaobin.com/test/jquery-3.2.1.js"></script> <script type="text/javascript" src="https://www.idaobin.com/test/ajaxfileupload.js"></script>
js:
<script type="text/javascript"> $(function () { //文件类型判断 $("#up").click(function () { var location = $("input[name='file']").val(); var point = location.lastIndexOf("."); var type = location.substr(point).toLowerCase(); var uploadFiles = document.getElementById("file1").files; var size = $("#file1")[0].files[0].size; if (uploadFiles.length == 0) { alert("请选择要上传的文件"); } else if((size/1024/1024)>1){ alert("超过文件上传限制"); } else if (type == ".zip" || type == ".rar") { ajaxFileUpload(); } else { alert("只允许上传.zip或者.rar格式的文件"); } }); }); function ajaxFileUpload() { $.ajaxFileUpload( { url: '/upload.aspx', //用于文件上传的服务器端请求地址 secureuri: false, //是否需要安全协议,一般设置为false fileElementId: 'file1', //文件上传域的ID dataType: 'json', //返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { console.log(data.msg); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e)//服务器响应失败处理函数 { alert(e); } } ); return false; } </script>
注意:url: ‘/upload.aspx’的upload.aspx为上传的处理页面,也可以是一般程序处理类
html:
<p><input type="file" id="file1" name="file" /></p> <input type="button" id="up" value="上传" />
后端
upload.aspx.cs:
protected void Page_Load(object sender, EventArgs e) { HttpFileCollection files = Request.Files; string msg = string.Empty; string error = string.Empty; if (files.Count > 0) { string director = Server.MapPath("/uploads/"); //上传目录 if (!Directory.Exists(director)) { Directory.CreateDirectory(director); } string path = director + Path.GetFileName(files[0].FileName); if (File.Exists(path)) { msg = "上传失败,文件存在"; } if((files[0].ContentLength / 1000) > 1024000){ msg = "文件大小超过限制"; } else { files[0].SaveAs(path); //返回json数据 msg = "上传成功"; } string res = "{ error:'" + error + "', msg:'" + msg + "'}"; Response.Write(res); Response.End(); } }
Web.config文件上传大小限制
放在<configuration>标签下面
<system.webServer> <security> <requestFiltering > <requestLimits maxAllowedContentLength ="1073741824"></requestLimits> </requestFiltering> </security> </system.webServer>
放在<system.web>标签内
<httpRuntime maxRequestLength="1073741824" appRequestQueueLimit ="100" executionTimeout="3600" useFullyQualifiedRedirectUrl="true" requestValidationMode="2.0" />
原文链接:https://www.idaobin.com/archives/1922.html
让我恰个饭吧.ヘ( ̄ω ̄ヘ)
恰饭广告