Xhr Pending Asp Net Mvc Httppost File Upload
Updated : Upload Files in ASP.NET Core 1.0 (Form POST and jQuery Ajax)
Uploading files is a mutual requirement in spider web applications. In ASP.Net Core 1.0 uploading files and saving them on the server is quite easy. To that stop this commodity shows how to do just that.
Brainstorm by creating a new ASP.Cyberspace Core project. Then add HomeController to the controllers binder. So add UploadFiles view to Views > Abode folder of the application.
HTML class for uploading files
Open the UploadFiles view and add the following HTML markup in it:
<form asp-action="UploadFiles" asp-controller="Home" method="post" enctype="multipart/form-data"> <input type="file" name="files" multiple /> <input type="submit" value="Upload Selected Files" /> </form>
The to a higher place markup uses grade tag helper of ASP.NET Core MVC. The asp-activity aspect indicates that the form volition be processed by the UploadFiles activity upon submission. The asp-controller attribute specifies the name of the controller containing the action method. The form is submitted using POST method. The enctype attribute of the form is set to multipart/form-data indicating that it volition be used for file upload operation.
The form contains an input field of type file. The name attribute of the file input field is set to files and the presence of multiple attribute indicates that multiple files tin be uploaded at once. The submit button submits the form to the server.
If you run the application at this phase, the UploadFiles view should look like this:
Constructor and UploadFiles() Get action
Now, open the HomeController and add a constructor to information technology as shown beneath:
public class HomeController : Controller { individual IHostingEnvironment hostingEnv; public HomeController(IHostingEnvironment env) { this.hostingEnv = env; } }
The constructor has a parameter of type IHostingEnvironment (Microsoft.AspNet.Hosting namespace). This parameter will be injected by MVC framework into the constructor. You need this parameter to construct the full path for saving the uploaded files. The IHostingEnvironment object is saved into a local variable for later on utilize.
And so add UploadFiles() activity for Get requests as shown below:
public IActionResult UploadFiles() { return View(); }
UploadFiles() POST action
Finally, add UploadFiles() activity for treatment the Mail service requests.
[HttpPost] public IActionResult UploadFiles(IList<IFormFile> files) { long size = 0; foreach(var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = hostingEnv.WebRootPath + $@"\{fileName}"; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Affluent(); } } ViewBag.Message = $"{files.Count} file(s) / {size} bytes uploaded successfully!"; return View(); }
The UploadFiles() activeness has a parameter - IList<IFormFile> - to receive the uploaded files. The IFormFile object represents a unmarried uploaded file. Within, a size variable keeps rail of how much data is being uploaded. Then a foreach loop iterates through the files collection.
The client side file proper noun of an uploaded file is extracted using the ContentDispositionHeaderValue form (Microsoft.Internet.Http.Headers namespace) and the ContentDisposition property of the IFormFile object. Let'southward assume that you wish to save the uploaded files into the wwwroot folder. And so, to arrive at the full path y'all utilize the WebRootPath property of IHostingEnvironment and append the filename to information technology.
Finally, the file is saved by the lawmaking inside the using cake. That code basically creates a new FileStream and copies the uploaded file into it. This is done using the Create() and the CopyTo() methods. A bulletin is stored in ViewBag to be displayed to the finish user.
The following effigy shows a sample successful run of the application:
Using jQuery Ajax to upload the files
In the preceding example y'all used class Postal service to submit the files to the server. What if you wish to ship files through Ajax? You lot can accomplish the job with a picayune fleck of modify to the <form> and the action.
Modify the <form> to accept a plain push button push button instead of submit button as shown below:
<form method="postal service" enctype="multipart/form-data"> <input blazon="file" id="files" proper name="files" multiple /> <input blazon="button" id="upload" value="Upload Selected Files" /> </form>
Then add a <script> reference to the jQuery library and write the following code to handle the click event of the upload button:
$(document).set up(function () { $("#upload").click(role (evt) { var fileUpload = $("#files").get(0); var files = fileUpload.files; var information = new FormData(); for (var i = 0; i < files.length ; i++) { information.append(files[i].name, files[i]); } $.ajax({ blazon: "POST", url: "/domicile/UploadFilesAjax", contentType: false, processData: fake, data: data, success: office (bulletin) { alert(bulletin); }, error: function () { alert("There was error uploading files!"); } }); }); });
The above code grabs each file from the file field and adds information technology to a FormData object (HTML5 feature). Then $.ajax() method POSTs the FormData object to the UploadFilesAjax() action of the HomeController. Notice that the contentType and processData properties are set to false since the FormData contains multipart/form-information content. The data property holds the FormData object.
Finally, add UploadFilesAjax() activity every bit follows:
[HttpPost] public IActionResult UploadFilesAjax() { long size = 0; var files = Asking.Form.Files; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = hostingEnv.WebRootPath + $@"\{filename}"; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } string bulletin = $"{files.Count} file(southward) / {size} bytes uploaded successfully!"; return Json(message); }
The lawmaking inside UploadFilesAjax() is quite like to UploadFiles() you wrote earlier. The primary difference is how the files are received. The UploadFilesAjax() doesn't accept IList<IFormFile> parameter. Instead it receives the files through the Asking.Grade.Files belongings. Secondly, the UploadFilesAjax() activity returns a JSON string message to the caller for the sake of displaying in the browser.
That'due south it for now! Keep coding!!
Source: http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx
0 Response to "Xhr Pending Asp Net Mvc Httppost File Upload"
Post a Comment