Skip to content Skip to sidebar Skip to footer

Uploading Files To Parse.com With Javascript

I'm attempting to upload an array of files to parse using javascript with the following code: html:

Solution 1:

Be careful with async code. Currently your code will have a race condition that will most likely fail because you call newStore.save() before parseFile.save() is finished.

Those 3 lines dealing with newStore should be inside the success handler for parseFile.save(), e.g.:

parseFile.save().then(function() {
    // The file has been saved to Parse.
    var newStore = new Parse.Object("FileStore");
    newStore.set("files", filesArray);
    newStore.save();
}, function(error) {
    // The file either could not be read, or could not be saved to Parse.
});

When you get to saving multiple files you'll need to wait for all of them to finish before moving to the next step. You can chain your promises together to run in Series or in Parallel.

For what you want Parallel would work fine:

var fileSavePromises = [];

// assuming some code that creates each file has stored the Parse.File objects in an
// array called "filesToSave" but not yet called save
_.each(filesToSave, function(file) {
    fileSavePromises.push(file.save());
});

Parse.Promise.when(fileSavePromises).then(function() {
    // all files have saved now, do other stuff here
    var newStore = new Parse.Object("FileStore");
    newStore.set("files", filesToSave);
    newStore.save();
});

Solution 2:

I have managed to solve this with the help of @Timothy code, full code after edit:

    var fileUploadControl = $("input[type=file]")[0];
    var filesToSave = fileUploadControl.files;

    var fileSavePromises = [];

    // assuming some code that creates each file has stored the Parse.File objects in an
    // array called "filesToSave" but not yet called save
    _.each(filesToSave, function(file) {
        var parseFile = new Parse.File("photo.jpg", file);
        fileSavePromises.push(
            parseFile.save().then(function() {
              // The file has been saved to Parse.
              $.post("/i", {
                file: {
                  "__type": "File",
                  "url": parseFile.url(),
                  "name": parseFile.name()
                }
              });
            })
        );
    });

    Parse.Promise.when(fileSavePromises).then(function() {
        // all files have saved now, do other stuff here
        window.location.href = "/";
    });

Post a Comment for "Uploading Files To Parse.com With Javascript"