asp.net File Upload Instance Summary _ Practical Tips

Source: Internet
Author: User
Tags httpcontext save file stack trace 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.

Method One: Use the Web control FileUpload, upload to the Web site root directory.

Test.aspx Key Code:

Copy 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:

Copy Code code as follows:

protected void Button1_Click (object sender, EventArgs e)
{
if (fileupload1.hasfile)
{
Fileupload1.saveas (Server.MapPath ("~/") + Fileupload1.filename);
Label1.Text = "Upload success!" ";
}
}

Method Two: Use HTML control HtmlInputFile, upload to the website root directory.

Test.aspx Key Code:

Copy 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:

Copy Code code as follows:

protected void Button1_Click (object sender, EventArgs e)
{
if (File1. Postedfile.contentlength > 0)
{
File1. Postedfile.saveas (Server.MapPath ("~/") + Path.getfilename (file1. Postedfile.filename));
Label1.Text = "Upload success!" ";
}
}

Method Three: Use HTML element <input type= "file" .../>, upload to the site root directory through Request.Files.

Test.aspx Key Code:

Copy 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:

Copy 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).

Two: FileUpload control has HasFile property, used to determine whether the user chose to upload files, and the following two methods need to be judged by the size of the upload file ContentLength property, when the user did not choose to upload files, the property value of 0.

You can see that the FileUpload package is more advanced, but the flexibility is also slightly worse.

example, asp.net file upload class (get file suffix name, save file, add text watermark)

Copy Code 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 Uploadobj
{

Public Uploadobj ()
{
//
TODO: Add constructor logic here
//
}
<summary>
Enumeration of types that allow file uploads
</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 detect file is legitimate
///<summary>
///detect upload file is valid
///</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;
}
#endregion

#region Save a 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)
{
string s = "";
String fileextends = "";
string fileName = Myfileupload.filename;
if (FileName!= "")
{
Get file suffix
Fileextends = EC. Uploadobj.getfileextends (FileName);
if (! EC. Uploadobj.checkfileextends (Fileextends))
{
EC. Messageobject.showpre ("Upload file type is illegal");
}
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>
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
}
To determine whether a 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. Length * fontsize;//of text
The following defines a rectangular area, which is then painted with a white background and a black word in the rectangle.
float rectx = 0;
float recty = 0;
float rectwidth = text. Length * (fontsize + 8);
Float Rectheight = fontsize + 8;
Declaring a rectangular field
RectangleF TextArea = new RectangleF (Rectx, Recty, Rectwidth, rectheight);
Font font = new Font ("XXFarEastFont-Arial", fontsize);//define Fonts
Brush Whitebrush = new SolidBrush (color.white)//White brush, drawing text
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 processing image, here for demonstration convenience, I will display the picture in 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 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 developers, that is, developers can process data streams as before, which is also done in httpruntime.
Requestlengthdiskthreshold property to set thresholds (threshold) with a default value of 256, that is, when a request exceeds 256KB, the hard disk is enabled as a cache, and this threshold is not related to whether the client is uploading content, Only care for requests from clients is 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 is handling 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 more repeating here


The code is as follows:

Copy Code code as follows:

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);

protected override void OnError (EventArgs e)
{
HttpContext ctx = HttpContext.Current;
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);
}

The ability to upload files requires more specific requirements--such as progress bar prompts, ASP. NET encapsulated controls 〈asp:fileupload/〉 is powerless.

A 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's upload components, which not only provide a better upload experience than the 〈input Type= "file" label on the page of the text box, Button beautiful, this 〈input type= "file" tag is not able to add styles through CSS, but someone tried 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

The support available with the 〈input type= "file"/〉 tag is very limited, and some special requirements that we cannot implement--or simply cannot be implemented easily and directly. 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 the HttpModule and keep the page active, so that it does not time out, but also can track progress or cancel the upload, or through the HttpHandler implementation, through 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:

Copy Code code as follows:

Fileuploader.net (mediachase Company, $310 above)
Radupload (Telerik Company, $249)
Neatupload (free, comply with LGPL agreement)

······

Neatupload is to intercept the current HttpWorkerRequest object in the BeginRequest event of the ASP.net pipeline, and then directly call its readentitybody to get the data stream passed by the client. and analyzed and dealt with. 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!

Introduction to HttpWorkerRequest implementation

Using the implied httpworkerrequest, the Getpreloadedentitybody and Readentitybody methods are used to read data from the pipe built by IIS for asp.net to upload files. The implementation method is as follows:

Copy Code code 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.