Already tried This Answer but it did not work. So seeking help.
I have a .Net 6 Razor page from where I am trying to upload a file.
Here is my AjaxFileUpload.CSHtml
<h3>Ajax File Upload</h3>
<form method="post">
<div class="mb-3">
<label for="formFile" class="form-label">Select File 1</label>
<input class="form-control" type="file" id="formFile1">
<br/>
<button type="button" class="btn btn-info" onclick="UploadFile1ViaAjax()">Upload File 1</button>
<span id="File1UploadStatus"></span>
</div>
</form>
The Ajax Call
<script>
function UploadFile1ViaAjax()
{
var file1 = $('#formFile1').prop("files")[0];
var url = "/Employees/AjaxFileUpload?handler=UploadFile1";
formData = new FormData();
formData.append(file1.name, file1);
alert("Uploading file 1 : " + file1.name);
$.ajax({
type: "POST",
url: url,
contentType: 'multipart/form-data',
contentType: false,
processData: false,
data: formData,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (result) {
alert("success: " + JSON.stringify(result));
},
failure: function (result) {
alert("failure");
},
error: function (result) {
alert("error");
},
}).done(function (result) {
alert("ajax call complete.");
});
}
</script>
Finally here is the code behind method AjaxFileUpload.CSHtml.cs
public IActionResult OnPostUploadFile1(IFormFile formData)
{
if (formData != null)
{
return new ObjectResult(new { status = "success" });
}
return new ObjectResult(new { status = "fail" });
}
When I upload a file and click the button, The ajax call works and debugger is hit in the code behind method, but the problem is, the IFormFile
object is always coming as null.
Why is this happening? How can I get the IFormFile
object populated with file data that I am uploading ?
The problem is because the name of the parameter inside your C# endpoint doesn't match the ajax call. Try setting the formdata.append("fileName", file)
and call the parameter in your endpoint fileName too. Other wise you should upload it either through submitting a form. Or uploading the file as base64