Hi there!
I'm trying to figure out how to upload a file to wwwroot/upload_files using ajax and .net. I have the backend setup and the file gets uploaded to the location successfully. However, I'm having trouble making it work with ajax, or maybe I'm not approaching it correctly.
Below is my index.cshtml view:
<input type="file" id="files" name="files" />
<input type="button" id="upload" value="Upload" />
Here is the ajax code:
$("#upload").click(function (evt) {
var fileUpload = $("#files");
$.ajax({
type: "POST",
url: "/FilesController/UploadFile",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was an error uploading files!");
}
});
});
And here's the controller:
[HttpPost("[action]")]
public async Task<IActionResult> UploadFile(IFormFile files) {
// Code logic for uploading file
}
You can see a working example in this image.
If you're facing similar issues, you can refer to these links for help:
- Ajax File Upload in ASP.NET Core Razor Pages
- Issues with .NET Core 6 file uploads
If anyone has suggestions on how to resolve this issue, your help would be greatly appreciated. Thank you!