异步 上传文件 ASP.NET
异步 上传文件 ASP.NET (以上传图片为例子)
html代码: <head> //所需要的两个JS <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script> </head> <img alt="" src="" id="img" style="display: none" /> <input id="fup" name="fup" type="file" /> <input id="btnUp" type="button" value="上传" onclick="ajaxFileUploads();"/> JS代码: function ajaxFileUploads() { $.ajaxFileUpload( { url:'Ajax_fileupload.aspx, secureuri:false, fileElementId:'fup', dataType: 'json', success: function (data, status) { if(data.err=="") { document.getElementById("img").style.display="block"; document.getElementById("img").src=data.msg; } else { $('#sperr').text(data.err); } }, error: function (data, status, e) { $('#sperr').text("上传失败!"); } }); } Ajax_fileupload.aspx页面: protected void Page_Load(object sender, EventArgs e) { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; HttpPostedFile file = files["fup"]; if (file.ContentLength <= Convert.ToInt32(SizeFunction() * 1024 * 1024)) //SizeFunction()获得文件限制大小 可以自己写在配置文件里,限制上传的大小 { if (IsValidFileType(file.FileName)) //验证文件类型 { string picPaht = Server.MapPath(FileFunciton()); //FileFunction() 文件保存的路径 这里的路径,名字 随自己要求设置,我这里最简单的日期了. Random rd = new Random(); string name = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000) + GetExtension(file.FileName); string strNewPath = GetSaveFilePath(picPaht) + name; file.SaveAs(strNewPath); Response.Write("{msg:'" + dal.ImgUrl() + name + "',err:''}"); } else { Response.Write("{msg:'',err:'类型错误!'}"); } } else { Response.Write("{msg:'',err:'大小错误!'}"); } } /// <summary> /// 验证文件类型 /// </summary> /// <param name="FileName"></param> /// <returns></returns> private bool IsValidFileType(string FileName) { string[] _AcceptedFileTypes = TypeFunction().Split('|'); //TypeFunction() 获得文件限制类型 这里我是以"|"分隔, 获得数组, 循环验证的 string ext = FileName.Substring(FileName.LastIndexOf(".") + 1, FileName.Length - FileName.LastIndexOf(".") - 1); for (int i = 0; i < _AcceptedFileTypes.Length; i++) { if (ext == _AcceptedFileTypes) { return true; } } return false; } /// <summary> /// 获得文件扩展名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GetExtension(string fileName) { try { int startPos = fileName.LastIndexOf("."); string ext = fileName.Substring(startPos, fileName.Length - startPos); return ext; } catch { return string.Empty; } } /// <summary> /// 创建文件要保存的路径 /// </summary> /// <param name="picPath">文件路径</param> /// <returns></returns> private string GetSaveFilePath(string picPath) { if (!Directory.Exists(picPath)) { Directory.CreateDirectory(picPath); } return picPath; } |