Skip to content

Instantly share code, notes, and snippets.

@jeffhuangtw
Created August 24, 2015 07:41
Show Gist options
  • Save jeffhuangtw/273455305ff8c39d1099 to your computer and use it in GitHub Desktop.
Save jeffhuangtw/273455305ff8c39d1099 to your computer and use it in GitHub Desktop.
Test fetch and upload multiple ParseFile with Promise
Parse.Cloud.define("TestUpload", function(request, response) {
var attachmentURLs = [];
attachmentURLs.push({'name': 'gogole_logo', 'url': 'https://www.google.com.tw/intl/en_ALL/images/srpr/logo11w.png', 'content-type': 'image/png'});
attachmentURLs.push({'name': 'yahoo_logo', 'url': 'https://www.google.com.tw/images/nav_logo225.png', 'content-type': 'image/png'});
var promises = [];
attachmentURLs.forEach(function(file){
promises.push(Parse.Cloud.httpRequest({
url: file.url,
}).then(function(fetchedFile){
console.log("fetchedFile buffer size:" + fetchedFile.buffer.length);
var base64 = fetchedFile.buffer.toString("base64");
var parseFile = new Parse.File(file.name, {base64: base64}, file['content-type']);
return parseFile.save();
}, function(error) {
console.log("upload parse file error:" + error);
})
);
});
Parse.Promise.when(promises).then(function(){
for (arg in arguments) {
console.log("ParseFile url: " + arguments[arg].url());
}
response.success('ok');
}, function(error) {
response.error(error);
});
});
@jeffhuangtw
Copy link
Author

Parse.Cloud.define("TestUpload", function(request, response) {
var attachmentURLs = [];
attachmentURLs.push({'name': 'gogole_logo', 'url': 'https://www.google.com.tw/intl/en_ALL/images/srpr/logo11w.png', 'content-type': 'image/png'});
attachmentURLs.push({'name': 'yahoo_logo', 'url': 'https://www.google.com.tw/images/nav_logo225.png', 'content-type': 'image/png'});

var promises = [];
attachmentURLs.forEach(function(file){
    promises.push(Parse.Cloud.httpRequest({
        url: file.url,
      }).then(function(fetchedFile){
        console.log("fetchedFile buffer size:" + fetchedFile.buffer.length);
        var base64 = fetchedFile.buffer.toString("base64");
        var parseFile = new Parse.File(file.name, {base64: base64}, file['content-type']);
        return parseFile.save();
      }, function(error) {
        console.log("upload parse file error:" + error);
      })
    );
});

//
Parse.Promise.when(promises).then(function(){
var imageList = [];
for (arg in arguments) {
console.log("ParseFile url: " + arguments[arg].url());
var data = new Object();
data.__type = "File";
data.name = arguments[arg].name();
data.url = arguments[arg].url();
imageList.push(data);
}

    var newObj = new Parse.Object("SomeClass");
    newObj.set("someArrayField", imageList);
    return newObj.save();
}).then(function(savedNewObject) {
    response.success('ok');
}, function(error) {
    response.error(error);
});

});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment