Reputation: 85
I am using MVC application where i used one drag and drop file upload which is working fine and file is uploading in respective folder.
Below is the sample code used for it:
<div id="dropZone" style="width:340px; height:200px">
<b> Drop your files here or</b>
</div>
<img id="uploadImg" src="~/Content/images/Cloud-File.gif" alt="uploadFile" style="width:297px; height:155px; display:none" />
$('#dropZone').filedrop({
url: '@Url.Action("UploadFiles","Home")',
paramname: 'files',
maxFiles: 5,
dragOver: function () {
//change color
},
dragLeave: function () {
//change color
},
drop: function () {
//change color
},
afterAll: function () {
},
uploadFinished: function (i, file, response, time)
{
//creating file size and showing the file name in list
}
});
Below is the controller used for it.
[HttpPost]
public ActionResult UploadFiles(IEnumerable files)
{
foreach (HttpPostedFileBase file in files)
{
//save logic
}
return Json("All files have been successfully stored.");
}
Till here everything is fine no issues after that i added one input file control for manual upload file also. Below is the jquery ajax call used for it:
$("#upload").change(function () {
var fileInfo = $("#upload").prop('files');
var fileData = new FormData();
fileData.append('files',fileInfo[0])
$.ajax({
type: "POST",
url: '@Url.Action("UploadFiles", "Home")',
processData:false,
// contentType: "application/json; charset=utf-8",
// data: { files: fileData},
dataType: "json",
async:false,
success: function (response) { UploadBrowseFile(fileInfo[0]); },
error: function (xhr, status, error) { alert(xhr.responseText); }
});
});
But it is not hitting the same controller action and process is moving to error function, Due to this manual upload is not working. Need help.
Upvotes: 0
Views: 1210
Reputation:
Your currently not sending any data to the method (the commented code for the data
option is incorrect), and you have the incorrect contentType
option for sending FormData
and it must be set to false
(the default is 'application/x-www-form-urlencoded; charset=UTF-8'
).
Change the ajax option to
$.ajax({
type: "POST",
url: '@Url.Action("UploadFiles", "Home")',
processData:false,
contentType: false, // change
data: fileData, // change
dataType: "json",
async:false,
success: function (response) { UploadBrowseFile(fileInfo[0]); },
error: function (xhr, status, error) { alert(xhr.responseText); }
});
You also need to change the signature of the method to
[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
Upvotes: 2