Answer the question
In order to leave comments, you need to log in
What is the correct way to upload a file via AJAX in ASP.NET MVC?
The form:
<form id="fileUpload" action="@Url.Action("AddImage")" method="POST" enctype="multipart/form-data">
<input id="fileInput" type="file" />
<input type="submit" value="Upload file" id="btnFileUpload" />
</form>
</div>
[HttpPost]
public ActionResult AddImage(HttpPostedFileBase image)
{
string fileName = image.FileName;
image.SaveAs(Path.Combine(HttpContext.Current.Server.MapPath("/Images/"), fileName));
return View("Index");
}
$(document).ready(function () {
$('#btnFileUpload').click(function () {
var formData = new FormData();
var file = $('#fileInput').files[0];
formData.append("fileInput", file);
$.ajax({
url: 'Home/AddImage',
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("URA");
}
});
});
Answer the question
In order to leave comments, you need to log in
Errors in all three places :)
1. In the form, add the name attribute for the control
2. Code in the controller
[HttpPost]
public ActionResult AddImage()
{
HttpPostedFileBase image = Request.Files["fileInput"];
if (image != null && image.ContentLength > 0 && !string.IsNullOrEmpty(image.FileName))
{
string fileName = image.FileName;
image.SaveAs(Path.Combine(Server.MapPath("Images"), fileName));
}
return View("Index");
}
$(document).ready(function () {
$('#btnFileUpload').click(function() {
$('#fileUpload').submit(function(event) {
// обработка событий по отправке формы
});
});
});
But if you really want to get the file through jQuery, then
var file = $('#fileInput') .get()[0]. files[0];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question