Background
I have a function that POSTs a single image via AJAX. This function sends an image in base64 that has been submitted by the user.
function loadDoc(target) {
var file = target.files[0];
// this just checks the format, it can be ignored
if (validFileType(file)) {
var fr = new FileReader();
fr.onloadend = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/img_upload");
xhr.onload = function(e) {
if (xhr.status === 200) {
// do something with response
console.log(xhr.responseText)
} else {
// do stuff with error
console.log("Some error with the server!")
}
};
xhr.send(
// just sending file type and message to debug it on the server side
JSON.stringify({
file_type: file.type,
image: fr.result.slice(fr.result.indexOf("base64") + 7, -1),
message: "Apples"
})
);
};
fr.readAsDataURL(file);
} else {
console.log("Some error with file format!")
}
}
Problem
The issue here is that the server has problems decoding PNG images sometimes (generally but not restricted to very large images), displaying Invalid byte errors. I am limiting the image size on the server but it is not causing the problem and it always works with JPG images.
Question(s)
Is this the proper way to send a single image to the server? Should I be using a form? In that case, what is the best way of using it without relying upon an external library? Maybe, is the error caused by the JSON.stringify call? Of course, it could always be an issue with the base64 decoder or the web framework I am using.
Whole example
Check the source at https://github.com/carrascomj/dalted or the web app at https://dalted.tech.