When passing an uploaded file through ajax to an asp.net MVC controller, the file property is showing a null value in the controller.
The image file object is obtained using
document.getElementById('fileUpload').files[0]
, then converted to JSON.stringify(fileName)
. However, when this object is passed to the asp.net MVC controller, it appears as null in the controller.
If anyone knows how to successfully pass a file from ajax to an MVC controller, please share your solution.
Admin controller
[HttpPost]
public string AddRetailer(HttpPostedFileBase file, string storeName, string storeUrl, string ecommercePlatform)
{
try {
Bswayed.Admin.Retailer retailer = new Bswayed.Admin.Retailer();
return JsonConvert.SerializeObject(data);
} catch (Exception ex) {
throw ex;
}
}
Asp.net upload form
<input type="file" id="fileUpload" name="fileUpload" onchange="this.parentNode.nextSibling.value=this.value"/>Browse
<input class="input-lg"
@Html.TextBoxFor(Model=>Model.StoreLogo, new { <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c7dbd6d4d2dfd8dbd3d2c58af7e1ded2c0f5d6d099e4c3d8c5d2fbd8d0d8">[email protected]</a>})
JavaScript(Ajax)
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload').files[0]
$.ajax({
url: $("#addRetailer").val(),
cache: false,
type: "POST",
data: {
file: JSON.stringify(fileName),
storeName: storeName,
storeUrl: storeUrl,
ecommercePlatform: ecommercePlatform
},
dataType: "json",
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}
}