Reputation: 10723
Here is how I call the method:
$.ajax({ url: "MyController/Mymethod", type: "POST", data: { file: file.files[0] } })
And here is the method:
[HttpPost]
public ActionResult Mymethod(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/images/location"), "petko.jpg");
file.SaveAs(path);
}
return RedirectToAction("Index");
}
file: file.files[0] is of type File. The method never gets called. Why?
Upvotes: 0
Views: 85
Reputation: 27292
I would start by providing an error function on your AJAX call so you can get some idea about what's happening on the client side. Example:
$.ajax({
url: "MyController/Mymethod",
type: "POST",
data: { file: file.files[0] },
error: function(jqXHR, textStatus, errorThrown) {
alert( textStatus + ": " + errorThrown );
}
success: function(data, textStatus, jqXHR) {
alert( "success: " + textStatus );
}
});
I assume you've already set a breakpoint inside your controller to verify that it's actually not getting called.
Upvotes: 0
Reputation: 8166
While I know that the question is asking why your method never gets called, how are you populating file.files? If this is a input of type file on your page, the upload doesn't occur until the form is submitted, so using your method, it will never post the file to your controller anyways.
Javascript does not have access to the file system due to security reasons. If you're trying to do an ajaxy file upload, you may want to look into Flash based uploaders such as Uploadify or SWFUpload
Upvotes: 2