有没有办法将多个文件上传到Firebase存储.它可以在单次尝试中上传单个文件,如下所示.
fileButton.addEventListener('change', function(e){ //Get file var file = e.target.files[0]; //Create storage reference var storageRef = firebase.storage().ref(DirectryPath+"/"+file.name); //Upload file var task = storageRef.put(file); //Update progress bar task.on('state_changed', function progress(snapshot){ var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100; uploader.value = percentage; }, function error(err){ }, function complete(){ var downloadURL = task.snapshot.downloadURL; } ); });
如何将多个文件上传到Firebase存储.
我找到了上述问题的解决方案,我想把它放在这里因为它对任何人都有用.
//Listen for file selection fileButton.addEventListener('change', function(e){ //Get files for (var i = 0; i < e.target.files.length; i++) { var imageFile = e.target.files[i]; uploadImageAsPromise(imageFile); } }); //Handle waiting to upload each file using promise function uploadImageAsPromise (imageFile) { return new Promise(function (resolve, reject) { var storageRef = firebase.storage().ref(fullDirectory+"/"+imageFile.name); //Upload file var task = storageRef.put(imageFile); //Update progress bar task.on('state_changed', function progress(snapshot){ var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100; uploader.value = percentage; }, function error(err){ }, function complete(){ var downloadURL = task.snapshot.downloadURL; } ); }); }
Firebase存储使用Promise,因此您可以使用Promises来实现它.
以下是涉及此主题的firebase博客文章: 保持我们的承诺(和回调)
给Promise.all()一个"承诺数组"
Promise.all( // Array of "Promises" myItems.map(item => putStorageItem(item)) ) .then((url) => { console.log(`All success`) }) .catch((error) => { console.log(`Some failed: `, error.message) });
上传每个文件并返回Promise
putStorageItem(item) { // the return value will be a Promise return firebase.storage().ref("YourPath").put("YourFile") .then((snapshot) => { console.log('One success:', item) }).catch((error) => { console.log('One failed:', item, error.message) }); }
YourPath
并且YourFile
可以用myItems
数组(因此item
对象)携带.
为了便于阅读,我在这里省略了它们,但是你得到了这个概念.
我相信有一个更简单的解决方案:
// set it up firebase.storage().ref().constructor.prototype.putFiles = function(files) { var ref = this; return Promise.all(files.map(function(file) { return ref.child(file.name).put(file); })); } // use it! firebase.storage().ref().putFiles(files).then(function(metadatas) { // Get an array of file metadata }).catch(function(error) { // If any task fails, handle this });