Mvc Web Application Upload File Into Customized Directory
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. Information technology'south widely used in social nets, forums, online auctions, etc.
There are a variety of upload components in ASP.NET MVC that serve to resolve one or another upload tasks, for case you may demand to upload single or multiple files, work with files of pocket-size or very large size, transfer entire folders or files only, only upload images or preprsdfsdf s sd focess them beforehand. Thus, you lot demand to find the upload tool that is not but fast and reliable, merely besides suits your requirements.
Here nosotros'll explore which upload arroyo is better to use when, merely earlier that allow's have a look at ASP.NET MVC file upload in full 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. Let's examine the file upload process stride by step:
- A user visits a web page with an uploader (represented by View) and chooses files to be uploaded.
- When the upload is started, the uploader packs the files into a Post request and sends this request to the server.
- ASP.Net caches all data in server memory or to disk depending on the uploaded file size.
- ASP.Cyberspace MVC defines the controller and advisable action method that will handle the request.
- The action method handles the request (for example, saves files on a hd, or updates a database, etc.) through the
Controller.Requestproperty, which gets theHttpPostedFilesBaseobject for the current request. - ASP.Internet MVC sends an answer to the customer through
Controller.Response.
You can configure file upload settings past specifying appropriate attributes in the web.config (or machine.config if you desire to make server-broad changes). Let's 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 data buffered in the server retention in kilobytes (the default value is eighty KB). -
executionTimeout– the allowed execution time for the asking before being automatically shut downward by ASP.NET (the default value is 110 seconds).
All these attributes should be specified in the <httpRuntime> department.
Notation: Avoid specifying "unlimited" (very large) values there. Specifying realistic limits, you can amend the functioning of your server or reduce the risk of DoS attacks.
Nosotros've basically described how ASP.Cyberspace MVC organizes file upload. Yet, if we look deeper into information technology, we'll understand that the file upload as well depends on the View implementation: it can be uncomplicated <input type="file"> elements, HTML5, Wink, Java, or preexisting tertiary-party uploader applications. Let'southward start with the first i – single file upload using the HTML command.
Single File Upload
This approach has quite limited functionality, simply it's notwithstanding the simplest mode to upload a unmarried file at a fourth dimension and will work in any popular browser.
Firstly, we consider the view. Our view consists of an HTML form containing the button, which opens a select file dialog, and Submit, which sends the chosen file to the server in a POST asking. The view code with razor syntax may look equally follows:
<h2>Bones File Upload</h2> @using (Html.BeginForm ("Index", "Dwelling house", FormMethod.Post, new { enctype = "multipart/grade-information" })) { <label for="file">Upload Image:</label> <input type="file" name="file" id="file"/><br><br> <input type="submit" value="Upload Paradigm"/> <br><br> @ViewBag.Bulletin } Let'south highlight the important parts:
- The
Html.BeginFormmethod creates an HTML form that includes the HTML file control, the submit push button, and a message, which declares whether the file is saved successfully or not. - The form method is
Postal service, and the form encoding type ismultipart/form-data. These parameters are required for uploading binary data to the server. - The
inputchemical element havingtype="file"displays the Choose File button and the field containing a selected file proper noun. - The
proper nameof theinputelement identifies the uploaded file in theHttpPostedFilesBaseobject.
After a user submits the form, the View sends posted data to the Action method of the Controller that handles file upload. Draw attention on theHttpPost attribute earlier the action method - information technology says that the Action should be triggered not only for regular Get requests, but also Mail requests. Otherwise it won't become the uploaded file.
Using this approach, y'all don't need to read the file from Request, because you lot can access the POSTed file directly through the HttpPostedFilesBase object due to model binding. The action model looks like this:
[HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) effort { 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.Message.ToString(); } else { ViewBag.Message = "You have not specified a file."; } return View(); } The action method receives the uploaded file, tries to salvage it to the Images folder, and shows a bulletin indicating whether or not the file is saved successfully. Note, the input control 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 following form:
In one case a user chooses a file and clicks the Upload Image button, the post-obit class with the bulletin (if the uploaded file is saved successfully) volition be shown:
Keep security in mind!
Notation: This simple awarding allows you to transfer the user's files to you server, merely it doesn't care about the security. The server may exist compromised past a virus or other malicious data uploaded past someone. Thus, you should add some file upload restrictions to the controller. There are several security concerns, which allow you lot to consider whether to take an uploaded file or not. For example, you can verify the checksum of the uploaded file or command file type past checking the extension (but this can be hands spoofed).
This approach is pretty skilful, if you upload a few pocket-size files one by one, simply it's rarely used due to the following disadvantages:
- Uploading a lot of files becomes a nightmare - a user has to click the Choose file push button for each file.
- Uploading large files is not convenient - the page freezes and doesn't display upload progress while the file upload is existence processed.
- Subsequently submitting the class all fields are cleared, thus if the form doesn't represent to validation, a user has to fill all the fields once more.
- Every browser displays the form in a different fashion:
Allow's encounter how we tin can get beyond the disadvantages of this HTML control.
Multiple Files Upload
The awarding we discussed above can be easily transformed to support multiple file upload: but specify as many file inputs in the view as the number of files y'all desire to be uploaded simultaneously. Note, all inputs should have the aforementioned name. This allows the ASP.Cyberspace MVC to accept an assortment of uploaded files and iterate through them in the action method. Nevertheless, in the case that a user needs to choose each file separately this is inconvenient, specially when uploading a large number of files.
Fortunately, there are many 3rd-party utilities supporting the multi-upload scenario and avoiding the shortcomings of the considered HTML command.
Whatever modern browser supports HTML5 and/or Flash, popular platforms which permit the creating of avant-garde file uploaders. Thus, there are a number of open source HTML5/Flash-based uploaders available with a large customs 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, car 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 complicated tasks, such as:
- Pre-procedure images earlier upload (resize, generate thumbnails of several sizes, add watermarks, extract EXIF, let users crop images, etc.).
- Upload entire folders and proceed the construction of the folders on the server.
- Upload hundreds of files.
- Upload files of hundreds of MB or even several GB.
- Automatically restore broken uploads.
- Speed up the upload process.
All these scenarios are ideal for Aurigma's Upload Suite. Yous can do information technology with few lines of code.
Encounter how to get started
Go a free thirty-day trial
Upload Suite includes premium uploaders based on various technologies (HTML5, Wink, Java, ActiveX) for whatsoever server technology – ASP.Cyberspace and PHP, archetype ASP and JSP, Cherry-red-on-rails and node.js.
Source: https://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc
0 Response to "Mvc Web Application Upload File Into Customized Directory"
Post a Comment