How Do You Upload a File in Asp.net?

How to upload files in ASP.NET

Nowadays you may find file upload in about every website – from forums that permit users to upload photos for their avatars, to online auctions where users tin can create galleries with a lot of images. The primary thing is that file upload should be fast, like shooting fish in a barrel, and reliable.

There are a number of different upload approaches in ASP.NET. Thus, it is essential to cull the ane that suits your requirements all-time: whether it is uploading a few files one past one or multiple files at a time, working with files of pocket-sized or very large size, sending entire folders or files only, having a simple image upload or preprocessing images beforehand.

In this article we consider different ways of file upload in ASP.Net and discuss their use, but before let's see how file upload works in general.

Files Upload Basics

The upload process is quite simple. At that place are e'er two parts, the client and server sides, that communicate with each other through HTTP requests and responses. Permit'south consider the usual upload scenario:

  1. A user visits a spider web folio and chooses files to upload.
  2. The client application packs these files to a Mail service asking and sends it to the server.
  3. The server parses the request, handles it (for case, saves files on a hard disk), and sends a response to the client side.

Yous tin can pattern a client side using dissimilar components: ASP.NET or HTML controls, HTML5, Flash, Java, or ready-to-apply upload applications. We will talk over them below.

Now permit's examine how the server works.

When the HTTP request is received, ASP.Cyberspace starts the uploading procedure: it caches all information in server memory or to deejay depending on the uploaded file size.

After all files are uploaded, the server code runs. Here is where you lot can handle uploaded data, for instance: save the uploaded files to the advisable location, examine their characteristics, update a database, etc.

Using ASP.NET you lot don't need to parse the HTTP request manually, yous just refer to the uploaded files through the HttpPostedFile collection. This makes life easier, because all you lot need is to iterate through each file in this collection and perform the necessary actions.

When the server code execution is finished, the server cleans up the memory and sends an HTTP response to the client.

You lot tin can configure your ASP.NET application past editing the web.config (or machine.config if yous want to alter settings globally, for all ASP.NET applications on your server). There are several attributes in the <httpRuntime> section which are of import for the file upload:

  • maxRequestLength – the asking size limit in kilobytes (the default value is 4096 KB).
  • requestLengthDiskThreshold – the limit of data buffered in the server memory in kilobytes (the default value is lxxx KB).
  • executionTimeout – the immune execution fourth dimension for the asking before being automatically shut down by ASP.NET (the default value is 110 seconds).

Note: it is not recommended specifying very large (virtually unlimited) values equally it may lead to the gamble of DoS attacks.

We've figured out the files upload organization in ASP.NET, now information technology is time to examine different upload approaches. Let'due south beginning with the simplest one – using the standard ASP.NET FileUpload control.

Using FileUpload Control

FileUpload supports single and multiple file uploads. It allows a user to choose a file to be uploaded via the Browse push button. The control doesn't automatically save a selected file to the server, but it exposes the SaveAs method to perform this. Deploying FileUpload in your web awarding is very easy. Firstly, permit'southward discuss how to do it for uploading a unmarried file at a time.

Single File Upload

To add single file upload functionality in your website merely embed the FileUpload command to the <form> tag in the place where you lot want users to brandish the upload interface. The code may expect every bit follows:

<html>                   <head>         <championship>Upload Files</title>     </head> <body>     <form id="form1" runat="server">         <asp:FileUpload ID="FileUpload1" runat="server" />         <br/>         <asp:Push ID="UploadButton" runat="server"                      OnClick="UploadButton_Click"                     Text="Upload File" />         <br/>         <asp:Characterization ID="FileUploadedLabel" runat="server" />     </class> </body> </html>

After running this folio, y'all will see the following interface:

Simple file upload form in ASP.NET

Let's highlight the hard parts:

  1. The FileUpload control (like any other server control) needs to be included in the <form> tag.
  2. The form should accept the runat="server" attribute, which indicates that the form is candy on the server and the FileUpload control can exist accessed by server scripts.
  3. The form should likewise contain id, name, and method attributes. Typically they are automatically generated by ASP.Cyberspace.
  4. The onClick attribute of the Upload File push button specifies the event handler that processes file upload.

After a user clicks the Upload File button, the form data volition be sent to the server. The code of the Upload File push button click handler should wait similar this:

protected void UploadButton_Click(object sender, EventArgs e) {     if (FileUpload1.HasFile)                     endeavour         {             FileUpload1.SaveAs(Server.MapPath("~/uploads/") +                  FileUpload1.FileName);             FileUploadedLabel.Text = "File name: " +                  FileUpload1.PostedFile.FileName + "<br>" +                  FileUpload1.PostedFile.ContentLength + " kb<br>" +                  "Content type: " + FileUpload1.PostedFile.ContentType;         }         catch (Exception ex)         {             FileUploadedLabel.Text = "Fault: " + ex.Message.ToString();         }     else     {         FileUploadedLabel.Text = "You have non specified a file.";     } }

This upshot handler checks if any file has been specified, tries to save information technology to the uploads folder, and displays a message indicating whether the file has been saved successfully. Note that the FileUpload1 name is similar to the FileUpload id attribute in the client form discussed above.

When adding uncomplicated upload to you web application do non forget that it does not protect your server from the malicious files that a user can upload. There are several security concerns which can help you to consider whether accept an uploaded file. For instance, you can control the type of uploaded file by checking the extension (which can be easily spoofed) or the correct "magic number" in the file header.

To upload a unmarried file at a fourth dimension is very easy, merely it in rare utilise nowadays. If you lot are going to design your own site, nearly likely y'all will need to upload several files at a time. So, let's see how you tin can practice it.

Multiple Files Upload

The most important advantage of the FileUpload server command is the support of multiple file upload. To enable it, just slightly modify the client application considered higher up. Even so, yous should empathise that the multiple upload feature works correctly only in browsers that back up HTML5.

The merely alter required in the client application considered in a higher place is adding the AllowMultiple holding which specifies whether multiple files can exist selected for upload:

<html> <head>     <title>Upload Files</title> </caput> <body>     <form id="form1" runat="server">         <asp:FileUpload ID="FilesUpload" runat="server"                          AllowMultiple="true" />         <br/>         <asp:Button ID="UploadButton" runat="server"                      OnClick="UploadButton_Click"                     Text="Upload File" />         <br/>         <asp:Label ID="FileUploadedList" runat="server"/>     </course> </torso> </html>

The code behind the Upload File push also needs to exist modified: before saving a file, the UploadButton_Click event handler should iterate through all uploaded data. Now the handler code may wait equally follows:

protected void UploadButton_Click(object sender, EventArgs e) {     if (FilesUpload.HasFile)         foreach (HttpPostedFile uploadedFile in FilesUpload.PostedFiles)             try             {                 uploadedFile.SaveAs(Server.MapPath("~/uploads/") +                                      uploadedFile.FileName);                 FileUploadedList.Text += "File proper noun: " +                    uploadedFile.FileName + "<br>" +                    uploadedFile.ContentLength + " kb<br>" +                    "Content type: " + uploadedFile.ContentType + "<br><br>";             }             catch (Exception ex)             {                 FileUploadedList.Text = "ERROR: " + ex.Message.ToString();             }     else     {         FileUploadedList.Text = "You have not specified a file.";     } }

As a result, you will get the same upload interface, merely the text box displays the number of selected files:

Multiple file upload form for ASP.NET

The FileUpload control is great when y'all but upload a few modest files, but it has several disadvantages:

  1. There is no opportunity to brandish uploading progress.
  2. Uploading a large number of files is very inconvenient, because the page does not respond while the file upload is processed.
  3. If a browser does not support HTML5, it won't piece of work at all.
  4. Every browser displays information technology in a different way.

Fortunately, some third political party uploaders are partially gratuitous of these concerns. Let's discuss them.

Third Party File Uploaders

Nowadays all popular browsers support the Flash or newer HTML5 platform, which allows the creating of advanced file upload using Flex or JavaScript respectively. Thus, there are a lot of third-party uploaders. The virtually popular are open up source HTML5/Flash-based uploaders, for example:

  • Uploadify is a jQuery plugin with a queue of files that are non uploaded yet, a real-time progress bar for each file, custom upload limitation, etc.
  • Fine Uploader is a JavaScript plugin tool with multiple file selection, progress bar, auto and manual upload, paradigm preview, etc.
  • Plupload is an upload tool based on several platforms, which even includes some image processing functionality, etc.

These uploaders are very adept at multiple file upload, provide a unproblematic interface, and are supported by a big community of developers. However, the following tasks cannot be solved by these uploaders:

  • Preprocessing uploaded images (resize, crop, rotate, generate thumbnails, add together watermarks, etc.).
  • Uploading entire folders and keeping a folder'southward structure on the server.
  • Uploading a large amount of files.
  • Large files upload (of hundreds MB or fifty-fifty several GB).
  • Automated restore of the cleaved uploads.
  • Speeding up the upload procedure.

All these scenarios are ideal for Aurigma's Upload Suite. You tin do it with few lines of code.

Run into how to get started

Go a free thirty-day trial

Upload Suite includes premium uploaders based on diverse technologies (HTML5, Flash, Java, ActiveX) for any server technology – ASP.NET and PHP, archetype ASP and JSP, Ruby-on-track and node.js.

demainewastand.blogspot.com

Source: https://www.aurigma.com/upload-suite/developers/aspnet/how-to-upload-files-in-aspnet

0 Response to "How Do You Upload a File in Asp.net?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel