When you encounter a file upload, most developers may prefer to use the server control, although it is convenient, but not very good control, no flexibility.
Now give an example, using the HTML tag language flexible control file upload.
1. HTML part
<input type= "File" id= "UploadFile" name= "UploadFile" style= "Display:none;" /><a href= "#" id= "uploads" > Upload file </a><input type= "hidden" id= "txtfile" name= "txtfile" value= ""/> <div class= "img" ></div>
2. js section
<script type= "Text/javascript" > $ (document). Ready (function () {//click on the div trigger file's upload event $ (". img"). Click (function () {$ ("#uploadFile"). Click (); }); $ ("#uploads"). Click (function () {ajaxfileupload (); }); }); function Ajaxfileupload () {$.ajaxfileupload ({URL: '/ Plus/upload.aspx ',//server-side request address Secureuri:false for file upload,//Whether a security protocol is required, generally set to False fil Eelementid: ' UploadFile ',//File upload domain ID dataType: ' JSON ',//return value type is generally set to JSON Success:fu Nction (data, status)//server successfully responds to handler {$ ("#img1"). attr ("src", data.imgurl); $ ("#txtFile"). Val (Data.imgurl); if (typeof (Data.error)! = ' undefined ') {if (data.error! = ')} { alert (data.error); } else {alert (data.msg); }}, Error:function (data, status, E)//server response failure Handler {alert (e); } } ); return false; } </script>
3, Uoload.aspx.cs code section
protected void Page_Load (object sender, EventArgs e) {httpfilecollection files = request.files; String msg = string. Empty; String error = String. Empty; String Imgurl = String. Empty; if (Files. Count > 0) {string fileUrl = Server.MapPath ("/") + "uploadfiles\\scholar\\temp\\"; Get the physical path where the Web server is located//If the folder does not exist, create an if (! Directory.Exists (FILEURL)) {directory.createdirectory (FILEURL); The string fileName = DateTime.Now.ToString ("yyyymmddhhmmssfff") + files[0]. Filename.substring (Files[0]. Filename.indexof ('. ')); /modify file name Files[0]. SaveAs (FileUrl + fileName); Save the uploaded file to the folder in the specified server msg = "Upload succeeded!" The file size is: "+ ((float) files[0]. contentlength/(1024*1024)). ToString ("0.00") + "MB"; Imgurl = "/uploadfiles/scholar/temp/" + fileName; string res = "{error:"+ Error +" ', msg: ' "+ msg +" ', Imgurl: ' "+ Imgurl +" '} "; Response.Write (RES); Response.End (); }}