Reputation: 13
I try to upload image file using onclick
function and ajax is it possible ? I search about on how to upload image but only i can see is via click function. but I have a reason for this that's why i used onclick function. controller is always null value
<div class="col-md-2">
<div class="form-group">
@Html.LabelFor(x => x.ImagePath, new { @class = "form-label" })
<input type="file" name="file" id="files" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<button type="submit" id="btnUpload" class="btn btn-primary btn-sm" onclick="saveImage()"><i class="fas fa-save"></i> Submit Image</button>
</div>
</div>
and this is my jquery and ajax
function saveImage() {
var formData = new FormData();
formData.append('file', $('#files')[0].files[0]);
$.ajax({
url: '@Url.Action("index", "payable")',
type: 'POST',
data: formData,
traditional: true,
success: function (data) {
alert("success");
}
});
}
My controller
public ActionResult Index()
{
HttpPostedFileBase file = Request.Files[0];
string fileName = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
fileName = fileName + extension;
var ImagePath = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
file.SaveAs(fileName);
return View();
}
Upvotes: 0
Views: 763
Reputation: 828
try this code:
var ufiles = $("#fileInput")[0].files;
if (ufiles.length > 0) {
if (window.FormData !== undefined) {
var fileData = new FormData();
//handling multiple files or single file
for (var x = 0; x < ufiles.length; x++) {
fileData.append(ufiles[x].name, ufiles[x]);
}
$.ajax({
type: "POST",
url: "yourUrl",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
//do something with result
},
});
} else {
alert("This browser doesn't support HTML5 file uploads!"); //bootbox dependency
}
}
And on server side:
[HttpPost]
public JsonResult Index()
{
HttpPostedFileBase file = HttpContext.Request.Files[0];//this can be put under foreach for multiple files
string fileName = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
fileName = fileName + extension;
var ImagePath = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
file.SaveAs(fileName);
//now cause we are hadnling ajax
return Json(fileName,JsonRequestBehavior.AllowGet);
}
Upvotes: 2