Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax upload file in asp.net mvc

I have a file in my view

<form id="upload" enctype="multipart/form-data">    <input type="file" name="fileUpload" id="fileUpload" size="23" /> </form> 

and an ajax request

$.ajax({     url: '<%=Url.Action("JsonSave","Survey")  %>',     dataType: 'json',     processData: false,     contentType: "multipart/mixed",     data: {         Id: selectedRow.Id,         Value: 'some date was added by the user here :))'     },     cache: false,     success: function (data) {} }); 

but there is no file in the Request.Files. Whats wrong with the ajax request?

like image 742
CoffeeCode Avatar asked Mar 11 '10 20:03

CoffeeCode


People also ask

How to send File in AJAX Request in MVC?

Go to File->New->Project. Give a suitable name to the Application. Click OK. As you can see in the above image, two files are sent to C# ActionMethod, and both will be uploaded now.


Video Answer


2 Answers

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {     var formdata = new FormData(); //FormData object     var fileInput = document.getElementById('fileInput');     //Iterating through each files selected in fileInput     for (i = 0; i < fileInput.files.length; i++) {         //Appending each file to FormData object         formdata.append(fileInput.files[i].name, fileInput.files[i]);     }     //Creating an XMLHttpRequest and sending     var xhr = new XMLHttpRequest();     xhr.open('POST', '/Home/Upload');     xhr.send(formdata);     xhr.onreadystatechange = function () {         if (xhr.readyState == 4 && xhr.status == 200) {             alert(xhr.responseText);         }     }     return false; }    

Controller

public JsonResult Upload() {     for (int i = 0; i < Request.Files.Count; i++)     {         HttpPostedFileBase file = Request.Files[i]; //Uploaded file         //Use the following properties to get file's name, size and MIMEType         int fileSize = file.ContentLength;         string fileName = file.FileName;         string mimeType = file.ContentType;         System.IO.Stream fileContent = file.InputStream;         //To save file, use SaveAs method         file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root     }     return Json("Uploaded " + Request.Files.Count + " files"); } 

EDIT : The HTML

<form id="uploader">     <input id="fileInput" type="file" multiple>     <input type="submit" value="Upload file" /> </form> 
like image 171
Ajeesh M Avatar answered Sep 19 '22 03:09

Ajeesh M


AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.

As the OP specifically asked for a jQuery implementation, here you go:

<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">     <input type="file" name="fileUpload" id="fileUpload" size="23" /><br />     <button>Upload!</button> </form> 
$('#upload').submit(function(e) {     e.preventDefault(); // stop the standard form submission      $.ajax({         url: this.action,         type: this.method,         data: new FormData(this),         cache: false,         contentType: false,         processData: false,         success: function (data) {             console.log(data.UploadedFileCount + ' file(s) uploaded successfully');         },         error: function(xhr, error, status) {             console.log(error, status);         }     }); }); 
public JsonResult Survey() {     for (int i = 0; i < Request.Files.Count; i++)     {         var file = Request.Files[i];         // save file as required here...     }     return Json(new { UploadedFileCount = Request.Files.Count }); } 

More information on FormData at MDN

like image 33
Rory McCrossan Avatar answered Sep 20 '22 03:09

Rory McCrossan