Upload a File and Show It on View
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.
There are a variety of upload components in ASP.Internet MVC that serve to resolve one or some other upload tasks, for example you may need to upload single or multiple files, work with files of minor or very big size, transfer unabridged folders or files only, merely upload images or preprsdfsdf southward sd focess them beforehand. Thus, you need to find the upload tool that is not merely fast and reliable, but also suits your requirements.
Hither we'll explore which upload approach is meliorate to use when, but earlier that let's accept a await at ASP.Cyberspace MVC file upload in full general.
File Upload Nuts
During the file upload process, but two parts of the MVC model interact with each other – a view and a controller. Allow's examine the file upload process pace by step:
- A user visits a web page with an uploader (represented by View) and chooses files to exist uploaded.
- When the upload is started, the uploader packs the files into a Mail service 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.Net MVC defines the controller and advisable action method that will handle the request.
- The action method handles the request (for instance, saves files on a hard disk, or updates a database, etc.) through the
Controller.Requestproperty, which gets theHttpPostedFilesBaseobject for the current request. - ASP.Net MVC sends an answer to the client 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 meet 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 retentiveness in kilobytes (the default value is 80 KB). -
executionTimeout– the allowed execution time for the asking before being automatically close downwardly by ASP.NET (the default value is 110 seconds).
All these attributes should be specified in the <httpRuntime> department.
Annotation: Avoid specifying "unlimited" (very large) values there. Specifying realistic limits, yous can improve the performance of your server or reduce the gamble of DoS attacks.
Nosotros've basically described how ASP.Net MVC organizes file upload. Nonetheless, if we look deeper into information technology, we'll understand that the file upload also depends on the View implementation: information technology can be simple <input type="file"> elements, HTML5, Flash, Java, or preexisting 3rd-party uploader applications. Let'south first with the commencement one – single file upload using the HTML control.
Single File Upload
This approach has quite limited functionality, but it's still the simplest way to upload a single file at a time and will piece of 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 Mail asking. The view lawmaking with razor syntax may expect every bit follows:
<h2>Bones File Upload</h2> @using (Html.BeginForm ("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <label for="file">Upload Image:</label> <input blazon="file" proper noun="file" id="file"/><br><br> <input type="submit" value="Upload Image"/> <br><br> @ViewBag.Bulletin } Let'due 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 grade method is
POST, and the grade encoding type ismultipart/form-data. These parameters are required for uploading binary data to the server. - The
inputelement havingblazon="file"displays the Choose File button and the field containing a selected file name. - The
proper nameof theinputelement identifies the uploaded file in theHttpPostedFilesBaseobject.
After a user submits the form, the View sends posted data to the Activeness method of the Controller that handles file upload. Draw attention on theHttpPost attribute earlier the action method - information technology says that the Activeness should be triggered non but for regular GET requests, but also POST requests. Otherwise it won't get the uploaded file.
Using this arroyo, you don't need to read the file from Request, because you tin can admission the POSTed file directly through the HttpPostedFilesBase object due to model binding. The action model looks like this:
[HttpPost] public ActionResult Alphabetize(HttpPostedFileBase file) { if (file != nil && file.ContentLength > 0) try { cord path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName)); file.SaveAs(path); ViewBag.Message = "File uploaded successfully"; } catch (Exception ex) { ViewBag.Message = "Error:" + ex.Bulletin.ToString(); } else { ViewBag.Message = "Y'all have non specified a file."; } return View(); } The activity method receives the uploaded file, tries to save it to the Images folder, and shows a message indicating whether or not the file is saved successfully. Notation, the input control proper noun in the view has the aforementioned name as the HttpPostedFilesBase object (it's file in our case).
Afterwards running this application you will meet the following course:
Once a user chooses a file and clicks the Upload Image push button, the following form with the message (if the uploaded file is saved successfully) volition be shown:
Keep security in mind!
Note: This simple awarding allows you to transfer the user'due south files to y'all server, but it doesn't care near 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 permit you to consider whether to accept an uploaded file or not. For example, you can verify the checksum of the uploaded file or control file type past checking the extension (merely this can exist easily spoofed).
This approach is pretty proficient, if y'all upload a few pocket-sized files one by one, but it'due south rarely used due to the post-obit 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 user-friendly - the page freezes and doesn't display upload progress while the file upload is being processed.
- After submitting the grade all fields are cleared, thus if the form doesn't correspond to validation, a user has to fill all the fields again.
- Every browser displays the course in a different way:
Let'southward encounter how we can go beyond the disadvantages of this HTML control.
Multiple Files Upload
The application we discussed in a higher place can be easily transformed to support multiple file upload: just specify as many file inputs in the view as the number of files yous desire to exist uploaded simultaneously. Annotation, all inputs should accept the same proper name. This allows the ASP.NET MVC to accept an array of uploaded files and iterate through them in the action method. Nonetheless, 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 tertiary-party utilities supporting the multi-upload scenario and avoiding the shortcomings of the considered HTML control.
Whatever modern browser supports HTML5 and/or Flash, popular platforms which allow the creating of advanced file uploaders. Thus, at that place are a number of open source HTML5/Flash-based uploaders available with a large customs of developers, for instance:
- 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 option, progress bar, auto and manual upload, epitome preview, etc.
- Plupload is an upload tool based on several browser extensions, which includes some paradigm processing functionality.
These uploaders are very practiced at multiple file uploads and provide a simple interface, but they cannot perform more complicated tasks, such as:
- Pre-procedure images before upload (resize, generate thumbnails of several sizes, add watermarks, extract EXIF, let users ingather images, etc.).
- Upload entire folders and keep the structure 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 platonic for Aurigma's Upload Suite. You can do it with few lines of lawmaking.
Run across how to go 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, Scarlet-on-rails and node.js.
whiteflualinte1985.blogspot.com
Source: https://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc
0 Response to "Upload a File and Show It on View"
Post a Comment