asp.net File Upload Example

Source: Internet
Author: User
Tags bool config file upload httpcontext save file stack trace root directory silverlight

 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, the need for friends can refer to the following

Method One: Use the Web control FileUpload, upload to the Web site root directory.   test.aspx Key code:     Code as follows: <form id= "Form1" runat= "Server" > <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: protected void Button1_Click (object sender, EventArgs e) {    if (Fileuplo Cds. HasFile)     {    Fileupload1.saveas (Server.MapPath ("~/") + Fileupload1.filename);     Lab El1. Text = "Upload success!" ";    }     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: protected void Button1_Click (object sender, E Ventargs e) {    if (file1. Postedfile.contentlength > 0)     {    file1. Postedfile.saveas (Server.MapPath ("~/") + Path.getfilename (file1. Postedfile.filename));     Label1.Text = "Upload success!" ";    }     method three: <input type= "file" with HTML element/>, 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= "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: protected void Button1_Click (object sender, EventArgs e) {    if (Request). files["File"]. ContentLength > 0)     {    request.files["filE "]. SaveAs (Server.MapPath ("~/") + path.getfilename (request.files["file"). FileName));     Label1.Text = "Upload success!" ";    }     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>&NBsp public class uploadobj  {  public uploadobj ()   { // /TODO: Add constructor logic here  // }&nbsp ; <summary> ///allows file uploads of type enumeration  ///</summary>  public enum filetype  {  Jpg,gif, bmp,png }   #region get file suffix  ///<summary> ///get file suffix  ///</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));  fo R (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  {  . 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; }    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. Length * fontsize;//text  //below defines a rectangular area, later in this rectangle with white background black word   float rectx = 0;  float recty = 0;  Float rec Twidth = 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 processingThe biggest problem with file uploads is that the memory footprint is too high, as the entire file is loaded into memory for processing, causing the server-side memory exhaustion If the user uploads the file too large, or too many users are uploading at the same time. This view is in fact one-sided, for the early ASP.net 1.X, in order to process, the user uploaded content will be loaded into memory, which does cause problems, but in ASP.net 2.0 will already upload data over a certain number after the user has the hard disk in the temporary files, This is completely transparent to the developer, that is, the developer can process the data stream as before, which also sets the threshold (threshold) by the Requestlengthdiskthreshold property in HttpRuntime, with a default value of 256 , that is, a request content 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. Another problem with   is the timing of asp.net large file uploads. 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 = WebConfigurationManager.       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. Request.Url.ToString () +   "    Source:" + exception. Source +    "    Message:" + exception. Message +   "    Stack Trace:" + exception. StackTrace;         CTX. Response.Write (errorstring);         CTX. Server.ClearError ();         base. OnError (e);      }  &nbsp   requires more specific requirements for file upload functions-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 used in these methods, we have the choice:   Fileuploader.net (mediachase company, $310)    Radupload (Telerik Company, $249)     Neatupload (freeFees, compliance with the LGPL protocol)     Neatupload is the current BeginRequest object intercepted in the HttpWorkerRequest event of 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=new Byte[n]   while WR. Readentitybody (bs2,n) 〉0)   { }  } 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.