I'm trying to get an image file using Ajax and then save it as a Parse File. I'm new to the process and this is what i've got so far:
$.ajax({
type: "GET",
url: url,
headers:{'Content-Type':'image/jpeg','X-Requested-With':'XMLHttpRequest'},
processData: false,
success: function (data) {
var name = "photo.jpg";
var img = btoa(encodeURIComponent(data));
var parseFile = new Parse.File(name, { base64: img });
parseFile.save().then(function () {
console.log('Saved parse file: ' + parseFile.url());
}, function (error) {
console.log("error: " + error.message);
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('error on uploadPhoto: ' + xhr + ' ' + ajaxOptions + ' ' + thrownError);
}
});
The File seems to be saved but all I get is an empty file. The Parse Docs says that we can use a base64-encoded String or an array of byte values.
What I'm I doing wrong, is there a better approach?
I decided to use a different approach using an XMLHttpRequest. Here's the code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var reader = new window.FileReader();
reader.readAsDataURL(this.response);
reader.onloadend = function () {
var name = "photo.jpg";
var base64data = reader.result;
var parseFile = new Parse.File(name, {base64: base64data});
parseFile.save().then(function () {
console.log('Saved parse file: ' + parseFile.url());
}, function (error) {
console.log("error: " + error.message);
});
}
}
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
Now the file is being saved correctly as a Parse File.
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.