神刀安全网

File Upload Through JQuery AJAX In ASP.NET MVC

Introduction

In this article we will discuss about how to upload files through jQuery AJAX in ASP.NET MVC.

Using Code

Start implementation, I want to introduce FormData object which is available in browser. Because with the help of FormData, we will send files to server.

What is FormData?

As stated

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

We can create FormData objects like var tempObject = new FormData();

It contains the following methods:

  1. FormData.append(): It appends a new value to FormData object. If key is not exists then creates a new key.
  2. FormData.delete(): It deletes a key-value pair from object.
  3. FormData.entries(): It helps to iterate over all key-value pairs present in object.
  4. FormData.get(): It returns value of given key within FormData object.
  5. FromData.has(): It returns a Boolean value whether a given key is present inside object.
  6. FormData.keys(): It helps to get all keys present inside object.
  7. FormData.set(): It helps to set/update a new value to existing keys or add new key-value pair if doesn’t exist.
  8. FormData.values():  Returns an iterator allowing to go through all values of the key/value pairs contained in this object. 

In this way FormData helps to send files, value to server through AJAX request. However, one disadvantage is old browsers doesn’t support FormData object and its methods.

Next we will design a view( index.cshtml) page where we will add the following HTML upload control and JavaScript code.

View (Index.cshtml)

<input type="file" id="FileUpload1" />   <input type="button" id="btnUpload" value="Upload Files" />      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>   <script>   $(document).ready(function(){       $('#btnUpload').click(function () {              // Checking whether FormData is available in browser           if (window.FormData !== undefined) {                  var fileUpload = $("#FileUpload1").get(0);               var files = fileUpload.files;                              // Create FormData object               var fileData = new FormData();                  // Looping over all files and add it to FormData object               for (var i = 0; i < files.length; i++) {                   fileData.append(files[i].name, files[i]);               }                              // Adding one more key to FormData object               fileData.append('username', ‘Manas’);                  $.ajax({                   url: '/Home/UploadFiles',                   type: "POST",                   contentType: false, // Not to set any content header                   processData: false, // Not to process data                   data: fileData,                   success: function (result) {                       alert(result);                   },                   error: function (err) {                       alert(err.statusText);                   }               });           } else {               alert("FormData is not supported.");           }       });   });   </script>   

In preceding code, first it checks whether windows.FormData is valid in browse. Because, using FormData we will send data to server through AJAX request. Once FormData object presence checked, it creates a new object. Then it fetches files injected in upload control and loop over it to add files to FormData object.

Controller (HomeController.cs)

In HomeContoller we need to add the following action (UploadFiles) to save files from coming AJAX request. Here is the code:

[HttpPost]   public ActionResult UploadFiles()   {   // Checking no of files injected in Request object       if (Request.Files.Count > 0)       {           try           {               //  Get all files from Request object               HttpFileCollectionBase files = Request.Files;               for (int i = 0; i < files.Count; i++)               {                   //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";                   //string filename = Path.GetFileName(Request.Files[i].FileName);                      HttpPostedFileBase file = files[i];                   string fname;                      // Checking for Internet Explorer                   if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")                   {                       string[] testfiles = file.FileName.Split(new char[] { '//' });                       fname = testfiles[testfiles.Length - 1];                   }                   else                   {                       fname = file.FileName;                   }                      // Get the complete folder path and store the file inside it.                   fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);                   file.SaveAs(fname);               }               // Returns message that successfully uploaded               return Json("File Uploaded Successfully!");           }           catch (Exception ex)           {               return Json("Error occurred. Error details: " + ex.Message);           }       }       else       {           return Json("No files selected.");       }   }   

In preceding code, first it checks no. of files appended in Request object. Next, HttpFileCollectionBase class collects all files from request object. Once it collects all files, it loop over all files and save it one by one. After saving files it returns JSON data to browser that it is successfully uploaded, and if exception occurs then it send exception message in JSON format.

Above code is suitable for only one file at a time but if you want to upload multiple files then you need to go for a small change. That is: add an attribute called multiple in file upload control like the following:

<input type="file" id="FileUpload1" multiple />   

Except multiple tag everything will be same in View and Controller page.  You can also upload files through HTML form tag(without using AJAX), visit here The  form(HTML) tag  makes round trip to server but AJAX do not. On the other hand, if your file is larger then AJAX might throw TimeOut issue. You can overcome the issue with time out property of AJAX.

Reference

Conclusion

In this article we discussed how to upload files to server jQuery AJAX request. You can upload files in two ways: AJAX and without AJAX (through Form tag). Choose appropriate one as per your file size and environment.

原文  http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » File Upload Through JQuery AJAX In ASP.NET MVC

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮