<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");
}
});
});
<input id="fileInput" name="fileInput" type="file" />
[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) {
// обработка событий по отправке формы
});
});
});
<body>
<div>
<form id="fileUpload" action="@Url.Action("AddImage")" method="POST" enctype="multipart/form-data">
<input id="fileInput" type="file" />
<input type="button" value="Upload file" id="btnFileUpload" />
</form>
</div>
<script type="text/javascript">
$("#btnFileUpload").click(function() {
var formData = new FormData();
var file = document.getElementById("fileInput").files[0];
formData.append("fileInput", file);
$.ajax({
url: "Home/AddImage",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function() {
alert("URA");
}
});
});
</script>
</body>
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult AddImage(HttpPostedFileBase fileInput)
{
string fileName = fileInput.FileName;
var image = new Bitmap(fileInput.InputStream, false);
image.Save(Path.Combine(HttpContext.Server.MapPath("/Images/"), fileName));
return View("Index");
}