I am trying to parse a base64 string back to the image as a file, however it is giving me the following error
Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
It is quite strange since the base64 string was never modified, I need to reassemble the file to send it as FormData()
and that in PHP it can be processed as$_FILES
$(() => {
let img;
$(document).on('change', 'input', function (e) {
let file = event.target.files[0];
if (!file) {
e.preventDefault();
return;
}else{
let imageType = /image.*/;
if (!file.type.match(imageType)) {
e.preventDefault();
return;
}else {
let reader = new FileReader();
reader.onload = () => {
$('img').attr('src', reader.result);
img = reader.result;
}
reader.readAsDataURL(file);
}
}
});
$(document).on('click', 'button', function(e) {
e.preventDefault(); e.stopPropagation();
let rebuild = new FormData('img', atob( img ));
console.log( rebuild );
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file">
<img src=""><hr>
<button>Enviar</button>
The problem is that when you get an image as "data URL", the MIME Type is appended to it in front of it, along with the encoding, so your string is something like
So you have to remove that prefix, you can do something like
To remove it and then you can decode the rest: