使用javascript将文件上传到parse.com [英] Uploading files to parse.com with javascript
问题描述
我正在尝试上传文件数组,以使用javascript和以下代码进行解析:
I'm attempting to upload an array of files to parse using javascript with the following code:
html:
<fieldset>
<input type="file" name="fileselect" id="fileselect" multiple></input>
<input id="uploadbutton" type="button" value="Upload"> </input>
</fieldset>
JS:
$('#uploadbutton').click(function () {
var fileUploadControl = $("#fileselect")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "style.css";
var parseFile = new Parse.File(name, file);
var filesArray = [parseFile];
}
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
var newStore = new Parse.Object("FileStore");
newStore.set("files", filesArray);
newStore.save();
});
我正在上传一个名为FileStore的类,该类的键"files"当前设置为数组,我想保存一个文件数组.这是上传多个文件进行解析的最佳方法吗?我的代码目前无法正常工作.我的目标是让多个文件与班级中的每个对象相关联.
I am uploading to a class I have called FileStore with key "files" which is set to an array currently, and I would like to have hold an array of files. Is this the best way to go about uploading multiple files to parse? The code for me isn't working right now. My aim is to have multiple files associated with each object in my class.
推荐答案
请谨慎使用异步代码.当前,您的代码将具有竞争条件,很可能会失败,因为您在parseFile.save()
完成之前调用了newStore.save()
.
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.
处理newStore
的那三行应该放在parseFile.save()
的成功处理程序中,例如:
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.
对于您想要的东西,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();
});
这篇关于使用javascript将文件上传到parse.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!