Skip to content Skip to sidebar Skip to footer

How Do I Add a File Upload to Asp.net Mvc

How to Upload Files in ASP.NET MVC

Uploading files from a client computer to the remote server is quite a common task for many websites and applications. It's widely used in social nets, forums, online auctions, etc.

At that place are a variety of upload components in ASP.Net MVC that serve to resolve i or another upload tasks, for instance yous may need to upload unmarried or multiple files, work with files of pocket-size or very large size, transfer entire folders or files only, just upload images or preprsdfsdf due south sd focess them beforehand. Thus, you lot need to find the upload tool that is non only fast and reliable, but too suits your requirements.

Here we'll explore which upload approach is better to utilize when, simply before that let'southward take a look at ASP.NET MVC file upload in general.

File Upload Basics

During the file upload procedure, only two parts of the MVC model interact with each other – a view and a controller. Permit's examine the file upload process step by footstep:

  1. A user visits a web page with an uploader (represented by View) and chooses files to exist uploaded.
  2. When the upload is started, the uploader packs the files into a POST request and sends this request to the server.
  3. ASP.Cyberspace caches all data in server retentiveness or to deejay depending on the uploaded file size.
  4. ASP.NET MVC defines the controller and advisable activity method that will handle the request.
  5. The action method handles the request (for case, saves files on a hard disk drive, or updates a database, etc.) through the Controller.Request holding, which gets the HttpPostedFilesBase object for the current request.
  6. ASP.Net MVC sends an answer to the customer through Controller.Response.

You lot tin can configure file upload settings by specifying appropriate attributes in the spider web.config (or machine.config if you desire to brand server-wide changes). Permit'south see what attributes are used to limit the file upload:

  • maxRequestLength – the request size limit in kilobytes (the default value is 4096 KB).
  • requestLengthDiskThreshold – the limit of information buffered in the server memory in kilobytes (the default value is eighty KB).
  • executionTimeout – the allowed execution time for the request earlier being automatically shut down by ASP.Internet (the default value is 110 seconds).

All these attributes should be specified in the <httpRuntime> department.

Note: Avoid specifying "unlimited" (very large) values there. Specifying realistic limits, y'all can improve the performance of your server or reduce the risk of DoS attacks.

We've basically described how ASP.Cyberspace MVC organizes file upload. However, if we look deeper into information technology, we'll understand that the file upload besides depends on the View implementation: it tin be uncomplicated <input type="file"> elements, HTML5, Flash, Java, or preexisting third-party uploader applications. Allow's start with the first one – single file upload using the HTML command.

Single File Upload

This arroyo has quite express functionality, but it'south yet the simplest mode to upload a single file at a fourth dimension and will work in whatever popular browser.

Firstly, we consider the view. Our view consists of an HTML grade containing the button, which opens a select file dialog, and Submit, which sends the chosen file to the server in a POST request. The view code with razor syntax may look equally follows:

<h2>Basic File Upload</h2>   @using (Html.BeginForm ("Index",                           "Home",                           FormMethod.Mail service,                           new { enctype = "multipart/form-data" }))   {                         <label for="file">Upload Image:</label>       <input type="file" name="file" id="file"/><br><br>       <input type="submit" value="Upload Image"/>       <br><br>       @ViewBag.Message   }

Permit'southward highlight the of import parts:

  • The Html.BeginForm method creates an HTML form that includes the HTML file control, the submit button, and a message, which declares whether the file is saved successfully or not.
  • The form method is Post, and the form encoding type is multipart/form-data. These parameters are required for uploading binary information to the server.
  • The input element having blazon="file" displays the Choose File button and the field containing a selected file proper name.
  • The name of the input element identifies the uploaded file in the HttpPostedFilesBase object.

After a user submits the form, the View sends posted data to the Activity method of the Controller that handles file upload. Draw attention on theHttpPost attribute before the action method - it says that the Activeness should be triggered non simply for regular GET requests, just also Mail requests. Otherwise information technology won't get the uploaded file.

Using this approach, you don't need to read the file from Asking, because y'all can access the POSTed file directly through the HttpPostedFilesBase object due to model binding. The action model looks similar this:

[HttpPost]   public ActionResult Index(HttpPostedFileBase file)   {       if (file != null && file.ContentLength > 0)           try           {               string path = Path.Combine(Server.MapPath("~/Images"),                                          Path.GetFileName(file.FileName));               file.SaveAs(path);               ViewBag.Message = "File uploaded successfully";           }           catch (Exception ex)           {               ViewBag.Message = "Fault:" + ex.Bulletin.ToString();           }       else       {           ViewBag.Message = "You accept not specified a file.";       }       return View();   }

The action method receives the uploaded file, tries to save it to the Images binder, and shows a bulletin indicating whether or not the file is saved successfully. Note, the input control proper name in the view has the same proper noun as the HttpPostedFilesBase object (it's file in our case).

After running this application you will see the post-obit grade:

Simple file upload form in ASP.NET MVC application.

Once a user chooses a file and clicks the Upload Image button, the post-obit form with the message (if the uploaded file is saved successfully) will be shown:

Simple file upload form - upload succesfully completed (ASP.NET MVC)

Keep security in heed!

Notation: This unproblematic application allows you lot to transfer the user'southward files to you server, simply it doesn't care about the security. The server may be compromised by a virus or other malicious data uploaded by someone. Thus, you should add together some file upload restrictions to the controller. There are several security concerns, which allow you lot to consider whether to accept an uploaded file or not. For instance, you tin verify the checksum of the uploaded file or control file type past checking the extension (just this tin can be hands spoofed).

This approach is pretty good, if you upload a few small files one past 1, but it'due south rarely used due to the following disadvantages:

  • Uploading a lot of files becomes a nightmare - a user has to click the Choose file button for each file.
  • Uploading large files is not convenient - the folio freezes and doesn't brandish upload progress while the file upload is existence processed.
  • Afterward submitting the class all fields are cleared, thus if the form doesn't correspond to validation, a user has to fill up all the fields once again.
  • Every browser displays the form in a dissimilar way:

Variety of file upload forms in different browsers (ASP.NET MVC)

Allow's see how nosotros can become beyond the disadvantages of this HTML control.

Multiple Files Upload

The application we discussed above can be easily transformed to back up multiple file upload: merely specify every bit many file inputs in the view as the number of files you lot want to be uploaded simultaneously. Note, all inputs should take the same name. This allows the ASP.Cyberspace MVC to accept an array of uploaded files and iterate through them in the activeness method. However, in the case that a user needs to cull each file separately this is inconvenient, specially when uploading a large number of files.

Fortunately, in that location are many third-party utilities supporting the multi-upload scenario and avoiding the shortcomings of the considered HTML control.

Any modernistic browser supports HTML5 and/or Flash, popular platforms which allow the creating of advanced file uploaders. Thus, there are a number of open up source HTML5/Wink-based uploaders bachelor with a large community of developers, for example:

  • Uploadify is a jQuery plugin which allows you to build an upload interface like to Gmail attachments.
  • Fine Uploader is a JavaScript plugin tool with multiple file selection, progress bar, auto and manual upload, image preview, etc.
  • Plupload is an upload tool based on several browser extensions, which includes some image processing functionality.

These uploaders are very good at multiple file uploads and provide a simple interface, but they cannot perform more than complicated tasks, such equally:

  • Pre-process images before upload (resize, generate thumbnails of several sizes, add watermarks, excerpt EXIF, let users crop images, etc.).
  • Upload entire folders and proceed the structure of the folders on the server.
  • Upload hundreds of files.
  • Upload files of hundreds of MB or even several GB.
  • Automatically restore cleaved uploads.
  • Speed up the upload procedure.

All these scenarios are ideal for Aurigma'southward Upload Suite. You tin do information technology with few lines of code.

See how to become started

Get a free 30-day trial

Upload Suite includes premium uploaders based on various technologies (HTML5, Flash, Java, ActiveX) for any server technology – ASP.Cyberspace and PHP, classic ASP and JSP, Ruby-on-rails and node.js.

holifieldlinto1976.blogspot.com

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

Post a Comment for "How Do I Add a File Upload to Asp.net Mvc"