asp. net file upload instance summary

  • 2020-11-03 22:06:15
  • OfStack

ASP.NET relies on the net framework class library, which encapsulates a large number of functions and makes uploading files very simple. There are three basic methods.

Method 1: Use the Web control FileUpload and upload to the site root.

Test.aspx key code:


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


     protected void Button1_Click(object sender, EventArgs e)
     {
         if (FileUpload1.HasFile)
         {
              FileUpload1.SaveAs(Server.MapPath("~/") + FileUpload1.FileName);
              Label1.Text = " Upload successful! ";
         }
     }

Method 2: Use the Html control HtmlInputFile and upload to the site root directory.

Test. aspx key code:


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


     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 successful! ";
         }
     }

Method 3: Use the Html element < input type = "file"... / > , through Request.Files uploaded to the site root directory.

Test. aspx Key code:


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


     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 successful! ";
         }
     }

Notice two differences:

FileUpload. FileName gets the file name of the client upload (without path), while file1.PostedFile. FileName and Request. Files["file"].FileName is different in different browsers: IE8 gets the fully qualified name of the client upload file (with path), while Google, apple and other browsers still get the file name (without path).

2: FileUpload control has the HasFile attribute, which is used to determine whether the user has chosen to upload a file, while the latter two methods need to determine the size of the uploaded file by the ContentLength attribute. When the user does not choose to upload a file, the value of this attribute is 0.

You can see that the FileUpload is more encapsulated, but less flexible.

Example, ES91en. net file upload class (get the file suffix name, save the file, add text watermark)


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> 
///  The upload class  
/// </summary> 
public class UploadObj 
{
public UploadObj() 
{ 
// 
// TODO:  Add the constructor logic here  
// 
} 
/// <summary> 
///  Enumeration of the types that allow file uploads  
/// </summary> 
public enum FileType 
{ 
jpg,gif,bmp,png 
}
#region  Get file suffixes  
/// <summary> 
///  Get file suffixes  
/// </summary> 
/// <param name="filename"> The 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  Check if the file is valid  
/// <summary> 
///  Check if the uploaded 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; 
} 
#endregion
#region  Save the file  
/// <summary> 
///  Save the file  
/// </summary> 
/// <param name="fpath"> The full path ,Server.MapPath()</param> 
/// <param name="myFileUpload"> File upload </param> 
/// <returns></returns> 
public static string PhotoSave(string fpath,FileUpload myFileUpload) 
{ 
string s = ""; 
string fileExtends = ""; 
string fileName = myFileUpload.FileName; 
if (fileName != "") 
{ 
// Get file suffixes  
fileExtends = EC.UploadObj.GetFileExtends(fileName); 
if (!EC.UploadObj.CheckFileExtends(fileExtends)) 
{ 
EC.MessageObject.ShowPre(" The 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> 
///  Add text watermark  
/// </summary> 
/// <param name="fileName"> File name path ( The 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; 
} 
// Determines 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;// The font size  
float textWidth = text.Length * fontSize;// Length of text  
// The following definitions 1 Rectangular region , Then draw black words on a white background inside the rectangle  
float rectX = 0; 
float rectY = 0; 
float rectWidth = text.Length * (fontSize + 8); 
float rectHeight = fontSize + 8; 
// Declare rectangular domain  
RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight); 
Font font = new Font(" Song typeface ", fontSize);// Define the font  
Brush whiteBrush = new SolidBrush(Color.White);// White brush , Words used  
Brush blackBrush = new SolidBrush(Color.Black);// Black brush for background  
g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight); 
g.DrawString(text, font, whiteBrush, textArea); 
MemoryStream ms = new MemoryStream(); 
bitmap.Save(ms, ImageFormat.Jpeg); 
// Output the processed image, here for demonstration convenience, I will display the image in the page  
//Response.Clear(); 
//Response.ContentType = "image/jpeg"; 
//Response.BinaryWrite(ms.ToArray()); 
g.Dispose(); 
bitmap.Dispose(); 
image.Dispose(); 
} 
#endregion 
} 
}

ASP. The disadvantages of NET

The biggest problem with ASP.NET for file uploads is the high memory footprint. Loading the entire file into memory for processing causes the server to run out of memory if the user uploads the file too large or too many users upload at the same time. This view is one-sided, for early ASP. NET 1. X, processing for applications, users to upload content will be fully loaded memory, it can cause problems, but in ASP. NET 2.0 will already have users to upload the data more than 1 after the specified amount to the hard disk in a temporary file, and this is for a developer completely transparent, that is to say, the developer can like before 1 sample data stream processing, this also in httpRuntime through
requestLengthDiskThreshold property to set the threshold (threshold), its default value is 256, that is, when a request content exceeds 256KB, the hard disk will be enabled as the cache, this threshold has nothing to do with whether the client is uploading the content, only CARES about the request sent by the client is greater than this value. Therefore, in ES114en.NET 2.0, the server's memory does not run out due to an exception request from the client. Another drawback is that the ES118en. NET handler will not process the request when it exceeds maxRequestLength (the default is 4M). This is completely different from ASP.NET throwing an exception, which is why if the user uploads a file that is too large, you don't see the error page specified in the ES122en.NET application (or the default), because ES124en.NET has not yet processed the request.


Another problem is dealing with the timeout for large file uploads of ES129en.NET. This can actually be handled by reading the httpRuntime section of ES131en.config at runtime and converting it to an HttpRuntimeSection object or overriding Page.OnError () to see if HTTP Code (corresponding code) is 400, which is not described here


The code is 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);  
    } 

For file uploads, there are special requirements - for example, progress bar prompts, the ASP.NET encapsulated control < asp:FileUpload / > is not available.

Good solution

Robert Bazinet advice, the best solution is to use RIA, in most cases, the suggested Silverlight or Flash upload component to replace the traditional FileUpload components, these components not only provides a better upload experience, is better than < input type = "file" > tags on the page of text boxes, buttons, beautiful, the < input type = "file" > tags can't through CSS add the style, But others have tried to fix it. There are no commercial upload components that use Silverlight so far, but here is a sample program that demonstrates multi-file uploads using Silverlight. Of course, using Silverlight, you can easily realize multi-threaded upload, breakpoint and continuation, these are not the content I want to discuss in detail, if you need to see for yourself.

Alternative solutions

The support provided by using the < input type="file" / > tag is very limited. There are some special requirements that we cannot implement -- or that we cannot implement easily or directly. So in order to do that we have to go around a big bend every time. In order to avoid a time-consuming detour every time we implement the same function, there are various upload components on the market or in the open source world, which provide packaged functions and make it much easier for us to implement the file upload function. For example, almost all upload components directly or indirectly provide progress hints, either with current percentage values or with a set of UI. Some components only provide a simple UI, while others provide a complete upload and delete management interface. In addition, some components provide the ability to prevent malicious uploads by clients.

I think the best solution is to block read a file and keep the page is activated in the HttpModule state, so as not to overtime, at the same time also can track progress or cancel the upload, or through HttpHandler implementation, through the progress bar to the user fully hint at the same time, also let developers to better control the size of the file, and upload that may occur during the process of abnormal. The upload component USES these methods. Our options are:


    FileUploader.NET  ( MediaChase The company, $310 Above)    
    RadUpload  ( Telerik The company, $249 )    
    NeatUpload  (Free, follow LGPL Protocol)  

·. ·

NeatUpload intercepts the current HttpWorkerRequest object in the BeginRequest event of ES192en.NET Pipeline, and then directly calls its ReadEntityBody and other methods to obtain the data flow passed by the client, analyze and process it. And get the status of the current upload by polling with the new request. For an introduction to NeatUpload and other open source components, see JeffreyZhao's upload file in the ES200en.NET application. Of course, he also says Memba Velodoc XP Edition and swfupload, very well written!

Introduction to HttpWorkerRequest implementation

Using the implicit HttpWorkerRequest, file uploads can be achieved by using its GetPreloadedEntityBody and ReadEntityBody methods to read data in blocks from pipe established for ES216en.NET. The implementation method 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 articles: