How to transmit a base64 string array from frontend to backend?

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!

hm, interesting issue! have u tried logging the encodedImages array before sending it? maybe it’s empty? also, check if ur contentType matches the server expectations. could u share the network tab details? sometimes the payload gets mangled in transit. oh, and make sure ur server can handle large payloads - base64 can get chunky!

I’ve encountered similar issues before. One potential problem is that your backend method is expecting a List, but you’re sending a JSON object with an ‘images’ property. Try modifying your C# method to accept a wrapper class:

public class ImageWrapper
{
    public List<string> images { get; set; }
}

[WebMethod]
public static string SaveImages(ImageWrapper wrapper)
{
    return $\"{wrapper.images.Count} images received\";
}

This should align with the JSON structure you’re sending from the frontend. Also, ensure your web.config is configured to accept large request sizes, as base64 strings can be quite long. If issues persist, consider implementing chunked file upload for better performance and reliability.

hey Sam, have u checked ur server’s max request size? base64 can get hefty. might need to tweak that in web.config. also, try console.logging encodedImages b4 sending - could be empty. if all else fails, maybe split the array into smaller chunks and send multiple requests. good luck mate!