I'm using .NET Core 6 (not MVC though). I'm trying to upload a file using AJAX that will also allow me to show a progress bar. I had this working in a PHP solution but carrying over to C# is proving to be difficult. Hoping someone can assist me.
I can see from the console that it's posting the file and sending everything however in C# I'm a bit lost on how to receive it. No matter what I've tried it's always null. Ultimately I'll be saving it as bytes to the db but it's important to have the ability to show progress of the upload.
The HTML
<input type="file" id="uploaddoc" style="display: none;" accept=".doc, .docx, .pdf, .png, .jpg, .jpeg" />
<input type="button" value="Browse..." class="btn btn-primary" style="max-width: 150px;"
onclick="document.getElementById('uploaddoc').click();" />
<div class="progress" id="progCollapse" style="position: absolute; height: 10px;
width: 425px; margin-left: -15px; margin-top: 5px; display: none">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
id="progress" style="width: 0" aria-valuenow="0" aria-valuemin="0"
aria-valuemax="100"></div></div>
The javascript
function uploadDoc() {
let file = document.getElementById("uploaddoc").files;
let data = { filename: this.value }
if (file.length > 0) {
let fileToLoad = file[0];
let fileReader = new FileReader();
$("#progCollapse").show()
document.getElementById("progress").style.width = "0%"
fileReader.onload = function (fileLoadedEvent) {
data.file = fileLoadedEvent.target.result;
$.ajax({
xhr: function () {
let xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
let percentComplete = evt.loaded / evt.total;
document.getElementById("progress").style.width = percentComplete * 100 + "%"
if (percentComplete === 1) {
$("#progCollapse").hide()
document.getElementById("progress").style.width = "0%"
}
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
let percentComplete = evt.loaded / evt.total;
document.getElementById("progress").style.width = "100%"
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
url: "/PageName?handler=SaveFile",
contentType: false,
processData: false,
data: { doc: fileReader.result },
success: function (data) {
}
});
};
fileReader.readAsDataURL(fileToLoad);
}
}
The C#
public OnPostSaveFile()
{
// This is where I'm stuck, what do I enter to receive the file correctly?
// I'm going to be converting it to bytes to save to the db
}