I am trying to post a form that has an input text field and also a file upload control using jquery ajax. However, I keep getting a 404 not found error. Below, I have included only the relevant part of razor code for brevity:
Here is a sample of the razor code:
<form id="uploadForm" asp-action="FileUpload" asp-controller="Content" method="post" enctype="multipart/form-data">
<input asp-for="Title" class="form-control" required />
<input asp-for="UploadFormFile">
<button type="button" id="uploadButton" class="btn btn-primary" >Upload</button>
</form>
Javascript:
$(document).ready(function () {
$("#uploadButton").click(function (e) {
var data = new FormData($("uploadForm").serialize());
var uploadedFile = $("#UploadFormFile").get(0).files[0];
data.append(uploadedFile.name, uploadedFile);
$.ajax({
url: '@Url.Action("FileUpload", "Content")',
type: "POST",
data: data,
contentType: false,
dataType: false,
processData: false,
success: function (result) {
alert(result);
}
});
});
});
Controller action:
[HttpPost]
public async Task<IActionResult> FileUpload()
{
CancellationToken cancellationToken = default(CancellationToken);
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = $@"\{filename}";
size += file.Length;
using (var fileStream = new FileStream(filename, FileMode.Create))
{
...
}
}
string message = $"{files.Count} file(s)/{ size} bytes uploaded successfully!";
return Json(message);
}
I tried using the answer here, but I still get a 404
The only time I did not get a 404 was when I changed the FormData to the below and did not append the uploaded file:
var data = new FormData($("uploadForm")[0]);
However, in this case, the controller action does not receive any data and the request.form was null.
So, is it possible to submit form data along with a file using jquery ajax in asp.net mvc core rc2?
Thanks.