I’m working on a project where I need to send a base64 string array from the frontend to the backend. I’ve tried using AJAX, but the array cells come up empty on the server side. Here’s what I’ve got so far:
// Frontend code
let encodedImages = [];
function convertToBase64(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async function handleFileUpload(event) {
let file = event.target.files[0];
let base64String = await convertToBase64(file);
encodedImages.push(base64String);
}
$('#sendButton').click(function() {
$.ajax({
url: '/api/saveImages',
type: 'POST',
data: JSON.stringify({ images: encodedImages }),
contentType: 'application/json',
success: function(response) {
console.log('Images saved:', response);
},
error: function(error) {
console.error('Error:', error);
}
});
});
// Backend code (C#)
[WebMethod]
public static string SaveImages(List<string> images)
{
// Process images here
return $"{images.Count} images received";
}
Any ideas on why the array might be coming through as null? I’m stumped!