I have a problem to send an image with my json, when receiving the body in the api, the "profile_image" attribute comes with no value, but it was suppose to come to base64's uri.
function getBase64(file) {
var reader = new FileReader();
reader.onloadend = function () {
reader.result;
};
reader.readAsDataURL(file);
return reader.result;
}
var file = document.getElementById("imgid").files[0];
var base64File = getBase64(file)
body = {
profile_image: base64File,
name: "test",
age: 19
}
$.ajax({
url:
"api.com/user",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ user: body }),
cache: false,
processData: false,
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
);
},
});
the method readAsDataURL
is an asynchronous method. the return statement would make the function ends up before the reader finishes the extraction.
var getBase64 = function (file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onloadend = function () {
base64String = reader.result;
resolve(reader.result);
};
reader.readAsDataURL(file);
})
}
var file = document.getElementById("imgid").files[0];
getBase64(file).then((base64String) => console.log(base64String) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.