maybe the title not right.bu i think you can understand my means.
In the asp.net world,we frequently uploading files via a web page, in this example,we will upload a file without refresh.
index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>无标题页</title> <script type="text/javascript" src="../js/jquery-1.3.2.min.js" charset="GB2312"></script> <script type="text/javascript"> $(function() { $("#btnUploadFile").click(function(){ $.ajax({ type: "post", dataType:"html", url: "upload.aspx", timeout: 20000, data: "userfile="+escape($("#userfile").val()), cache:false, beforeSend: function(XMLHttpRequest){ //ShowLoading(); }, success: function(data,textStatus){ $("#dialog").html(data); alert("succeed"); }, complete: function(XMLHttpRequest, textStatus){ //HideLoading(); }, error: function(){ //HappenError(); } }); }); }); </script> </head> <body> <form id="form1" method="post" enctype="multipart/form-data"> <div> <input id="userfile" type="file" /><input id="btnUploadFile" type="button" value="upload" /></div><div id="dialog"></div> </form> </body> </html> |
upload.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <%@ Page Language="C#" Debug="true" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Net" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { string requestpath = Request.Form["userfile"].ToString(); string _path = "../Users/";// string extName = "";// string fileNamePath = ""; // string NewFilePath = "";// FileInfo userPostedFile = new FileInfo(Server.UrlDecode(requestpath)); if (userPostedFile.Length > 0) { extName = userPostedFile.Extension; if (_path.EndsWith("/") == false) _path = _path + "/"; fileNamePath = HttpContext.Current.Server.MapPath(_path); NewFilePath = fileNamePath + DateTime.Now.ToString("yyyyMMddHHmmss") + extName; WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; FileStream fs = new FileStream(Server.UrlDecode(Context.Request.Form["userfile"]), FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(NewFilePath, "PUT"); if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); Response.Write("ok!"); } else { Response.Write("error!"); } postStream.Close(); postStream.Dispose(); } } </script> |

























































