File Upload in the asp.net there are many ways, here I would like to introduce you to the simplest and most convenient. net file upload instance, I hope to help you. NET Beginners.
Asp. NET relies on the. NET Framework class library, encapsulates a large number of functions, making uploading files very simple, there are mainly the following three basic methods. Method One: Use Web control fileupload, upload to Web site root directory. test.aspx Key code: Code as follows: <form id= "Form1" runat= "Server" > & Lt;asp:fileupload id= "FileUpload1" runat= "server"/> <asp:button id= "Button1" runat= "Server" text= "Upload" onclick= "button1_click"/> <asp:label id= "Label1" runat= "Server" text= "style=" Color:red "></asp:Label> </form> Test.aspx.cs key code: Code as follows: & nbsp protected void Button1_Click (object sender, EventArgs e) { &NBSP;IF (fileupload1.hasfile) { FILEUPLOAD1.SAV EAs (Server.MapPath ("~/") + Fileupload1.filename); Label1.Text = "Upload success!" "; &NBSP} &NBSP;} Method Two: Use HTML control HtmlInputFile, upload to Web site root directory. test.aspx Key code: Code as follows: <form id= "Form1" runat= "Server" > <input type = "File" id= "File1" runat= "server"/> <asp:button id= "Button1" runat= "server" text= "upload" OnClick = "Button1_Click"/> <asp:label id= "Label1" runat= "Server" text= "" style= "color:red" ></ asp:label> </form> Test.aspx.cs key code: Code as follows: &NBSP;PROTECTE d void Button1_Click (object sender, EventArgs e) { if (file1. Postedfile.contentlength > 0) { file 1.postedfile.saveas (Server.MapPath ("~/") + Path.getfilename (file1. Postedfile.filename)); Label1.Text = "Upload success!" "; &NBSP} } &NBsp Method Three: Use HTML element <input type= "file" .../>, upload to the site root directory through Request.Files. test.aspx Key code: Code as follows: <form id= "Form1" runat= "Server" enctype= "Multipart/form-data" > <input type= "file" name= "file"/> <asp:button id= "Button1" runat= "s Erver "text=" Upload "onclick=" button1_click/> <asp:label id= "Label1" runat= "Server" text= "" Style= "color:red" ></asp:Label> </form> Test.aspx.cs key code: Code as follows: protected void Button1_Click (object sender, EventArgs e) { &NBS P if (request.files["file"). ContentLength > 0) { request.files[ File "]. SaveAs (Server.MapPath ("~/") + path.getfilename (request.files["file"). FileName)); Label1.Text = "Upload success!" "; &NBSP} &NBSP} Note two differences: One: Fileupload.filename gets the client upload file name (without path), while File1.PostedFile.FileName and request.files["file". FileName in different browsers under different circumstances: IE8 to obtain the client upload file fully qualified name (with the path), Google, Apple and other browsers are still file name (without path). II: FileUpload Control has hasfile properties, to determine whether the user chose to upload files, and the following two methods to determine the size of the upload file ContentLength property, when the user did not choose to upload files, the property value of 0. can see that the FileUpload package is much higher, but the flexibility is also slightly worse. example, asp.net file upload class (get file suffix name, save file, add text watermark) code as follows: using system; using system.data; using System . configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using System.Web.UI.HtmlControls; using system.drawing; using system.io; using System.Drawing.Imaging; namespace ec { ///<summary> ///upload class ///</summary> public class Uploadob j { Public uploadobj () { // /TODO: hereAdd constructor logic // } ///<summary> ///allow file upload Type enumeration ///</summary> public enum F iletype { jpg,gif,bmp,png } #region get file suffix ///<summary> ///get file suffix ///& lt;/summary> ///<param name= "filename" > file name </param> ///<returns></returns> public static string Getfileextends (string filename) { string ext = null; if (filename. IndexOf ('. ') > 0) { string[] fs = filename. Split ('. '); ext = Fs[fs. length-1]; } return ext; } #endregion #region test file is legal ///<summary> // /Check upload file is legal ///</summary> ///<param name= "fileextends" > File suffix name </param> ///< returns></returns> public static bool Checkfileextends (string fileextends) { BOOL status = false; fileextends = Fileextends.tolower (); string[] Fe = enum.getnames (tyPeof (FileType)); for (int i = 0; i < Fe. Length; i++) { if (Fe[i]. ToLower () = fileextends) { status = true; break; } } return status; } #en Dregion #region Save file ///<summary> ///save file ///</summary> ///<param ' name= Fpath "> Full path, Server.MapPath () </param> ///<param name=" myfileupload "> Upload control </param> / <returns></returns> public static string Photosave (String fpath,fileupload myfileupload) {& nbsp string s = ""; string fileextends = ""; string fileName = myfileupload.filename; if (fileName!= "") &nbs P { //Get file suffix fileextends = EC. Uploadobj.getfileextends (FileName); if (! EC. Uploadobj.checkfileextends (fileextends)) { EC. Messageobject.showpre ("Upload file type is not valid"); } Random rd = new Random (); s = EC. Randomobject.daterndname (RD) + "." + fileextends; String file =Fpath + "" + s; try { myfileupload.saveas (file); } catch (Exception ee) { throw New Exception (EE. ToString ()); } } return s; } #endregion #region Add text watermark ///<SUMMARY>&NB Sp Add text watermark ///</summary> ///<param name= "fileName" > File name Path (full path) </param> ///< param name= "text" > File </param> public void addtexttoimg (string fileName, string text) { if (! File.exists (fileName)) { throw new FileNotFoundException ("file does not exist"); } if (Text = string. Empty) { return; } //Determining whether the file type is an image type System.Drawing.Image image = System.Drawing.Image.FromFile (fileName); Bitmap Bitmap = new Bitmap (image, image. Width, image. Height); Graphics g = graphics.fromimage (bitmap); float fontsize = 12.0f;//font size float textWidth = TEXT.L Ength * fontsize;//Text length //below defines a rectangular area, later in this rectangle with white background black word float Rectx = 0; Float recty = 0; float rectwidth = text. Length * (fontsize + 8); float rectheight = fontsize + 8; //Declaration rectangle field RectangleF TextArea = new RectangleF (r Ectx, Recty, Rectwidth, rectheight); font font = new Font ("XXFarEastFont-Arial", fontsize);//define font Brush Whitebrush = new SOLIDB Rush (Color.White)//white brush, painting text with Brush Blackbrush = new SolidBrush (color.black);//Black brush, drawing background G.fillrectangle ( Blackbrush, Rectx, Recty, Rectwidth, Rectheight; g.drawstring (text, font, Whitebrush, TextArea); MemoryStream ms = new MemoryStream (); bitmap. Save (MS, IMAGEFORMAT.JPEG); //output processed image, here for demonstration convenience, I will display the picture on the page //response.clear (); / Response.ContentType = "Image/jpeg"; //response.binarywrite (Ms. ToArray ()); g.dispose (); bitmap. Dispose (); image. Dispose (); } #endregion } } ASP. NET's drawbacks ASP. NET processing file upload the biggest problem is that memory footprint is too high, because the entire file loaded into memory processing, resulting in if the user upload files too large, or too many users simultaneously upload, will cause server-side memory exhaustion. This view is actually a piece ofSurface, for the early ASP.net 1.X, in order for the program to process, the user uploaded content will be completely loaded into memory, which does cause problems, but in ASP.net 2.0 has been uploaded data over a certain number of users in the temporary files on the hard disk, which is completely transparent to the developer , that is, the developer can process the data stream as before, which also sets the threshold value (threshold) by the Requestlengthdiskthreshold property in HttpRuntime, with a default value of 256, That is, a request content of more than 256KB will enable the hard disk as a cache, this threshold and whether the client is in the upload content is irrelevant, only concerned that the client sent a request greater than this value. As a result, the server's memory in asp.net 2.0 is not depleted because of an exception request from the client. Another disadvantage is that when the request exceeds the maxRequestLength (default 4M), the ASP. NET handler will not process the request. This is completely different from asp.net throwing an exception, which is why if the user uploads the file too large, the error page (or default) specified in the ASP.net application is not seen, because ASP.net has not yet processed the request. There is also a problem is to deal with asp.net large file upload timeout. This can actually be done by reading the httpruntime section in the web.config at run time and converting it to a Httpruntimesection object or rewriting Page.onerror () to detect if HTTP code (the corresponding code) is 400来 processing. No longer repeat here code as follows: Code: System.Configuration.Configuration config = Webc Onfigurationmanager. Openwebconfiguration ("~"); httpruntimesection section = config. GetSection ("System.web/httpruntime") as httpruntimesection; Double maxfilesize = math.round (section. maxrequestlength/1024.0, 1); String errorstring = string. Format ("Make sure Your file is under {0:0.#} MB.", MaxFileSize); Pro tected override void OnError (EventArgs e) { HttpContext CTX = Httpcontext.curren T Exception Exception = ctx. Server.GetLastError (); String errorstring = " offending URL:" + CTX.R Equest. Url.tostring () + " Source:" + exception. Source + " message:" + exception. Message + " Stack Trace:" + exception. StackTrace; CTX. Response.Write (errorstring); CTX. Server.ClearError (); base. OnError (e); } &NBsp for file upload features require a more specific requirements-such as progress bar prompts, ASP. NET encapsulated controls 〈asp:fileupload/〉 is powerless. Good solution Robert Bazinet suggests that the best solution is to use Ria, and in most cases it is recommended to replace the traditional fileupload components with Silverlight or flash upload components, This type of component does not just provide a better upload experience than the 〈input type= "file" tags on the page text boxes, buttons beautiful, this 〈input type= "file" tag is not able to add styles through CSS, but some people try to solve. No commercial upload component has been used in Silverlight so far, but there are sample programs that demonstrate multiple file uploads with Silverlight. Of course, the use of Silverlight can be very easy to implement multi-threaded upload, breakpoint continued to pass this function, these are not what I want to discuss in detail, if you need to be able to see for themselves. Alternative Solutions use 〈input type= "file"/〉 tags can provide very limited support, some special requirements we can not achieve--or can not easily, directly to achieve. So in order to achieve this function we have to go around a big bend every time. In order to avoid the same function every time to take the trouble to go through the detour, the market or open source has appeared a variety of upload components, upload components to provide a good package of functions, so that we realize the file upload function when a lot easier. For example, almost all of the upload components directly or indirectly provide the function of the progress prompts, some provide the current percentage value, some directly provide a set of UI, some components only provide a simple UI, and some provide a complete upload, delete the management interface. In addition, some components also provide the ability to prevent malicious uploads from the client. I think the best way is to read the file in HttpModule and keep the page active so that it does not time out, and can track progress or cancel the upload, or through the HttpHandler implementation, in the progress bar to give users a full hint of the same time, It also gives developers greater control over the size of the file and the exceptions that may occur during the upload process. Upload components are using these methods, our choice is: code as follows: Fileuploader.net (mediachase company, $310 above) Radupload (TeleRik Company, $249) Neatupload (free, Compliance LGPL protocol) Neatupload intercepted the current HttpWorkerRequest object in the BeginRequest event of the ASP.net pipeline. Then directly call its readentitybody and other methods to obtain the data stream passed by the client, and analyze and deal with it. And to get the status of the current upload by polling with the new request. An introduction to Neatupload and other open source components can be read in Jeffreyzhao's asp.net application, and of course he said Memba Velodoc XP Edition and SWFUpload, which is very good! HttpWorkerRequest implementation using implied httpworkerrequest, Using its Getpreloadedentitybody and Readentitybody method to read data from the pipe built by IIS for asp.net, file uploads can be realized. The implementation method is as follows: code is as follows: IServiceProvider provider= (IServiceProvider) HttpContext.Current; HttpWorkerRequest wr= (httpworkerrequest) provider. GetService (typeof (HttpWorkerRequest)); byte[] BS=WR. Getpreloadedentitybody (); if (!WR. Isentireentitybodyispreloaded ()) { int n=1024; byte[] Bs2=n EW Byte[n]; while (WR. Readentitybody (bs2,n) 〉0) { } }