Monday, 28 October 2013

Upload files using AJAX in ASP.Net MVC

This approach will work on almost all browsers but, you can't upload multiple files, and file information have to send separately. In this method file is send directly in XMLHttpRequest, and file information is send along with HTTP Headers.
js FILE
  1. window.onload = function () {
  2.     document.getElementById('uploader').onsubmit = function () {
  3.         var fileInput = document.getElementById('fileInput');
  4.         var xhr = new XMLHttpRequest();
  5.         xhr.open('POST', '/Home/Upload');
  6.         xhr.setRequestHeader('Content-type', 'multipart/form-data');
  7. //Appending file information in Http headers
  8.         xhr.setRequestHeader('X-File-Name', fileInput.files[0].name);
  9.         xhr.setRequestHeader('X-File-Type', fileInput.files[0].type);
  10.         xhr.setRequestHeader('X-File-Size', fileInput.files[0].size);
  11. //Sending file in XMLHttpRequest
  12.         xhr.send(fileInput.files[0]);
  13.         xhr.onreadystatechange = function () {
  14.             if (xhr.readyState == 4 && xhr.status == 200) {
  15.                 alert(xhr.responseText);
  16.             }
  17.         }
  18.         return false;
  19.     }
  20. }
Controller:
  1. [HttpPost]
  2. public JsonResult Upload()
  3. {
  4.     string fileName = Request.Headers["X-File-Name"];
  5.     string fileType = Request.Headers["X-File-Type"];
  6.     int fileSize = Convert.ToInt32(Request.Headers["X-File-Size"]);
  7. //File's content is available in Request.InputStream property
  8. System.IO.Stream fileContent = Request.InputStream;
  9. //Creating a FileStream to save file's content
  10. System.IO.FileStream fileStream = System.IO.File.Create(Server.MapPath("~/") + fileName);
  11. fileContent.Seek(0, System.IO.SeekOrigin.Begin);
  12. //Copying file's content to FileStream
  13. fileContent.CopyTo(fileStream);
  14. fileStream.Dispose();
  15. return Json("File uploaded");
Thats all and you are done :)

No comments:

Post a Comment