您的问题对于您要存储的信息有点模糊。所以我做了一些假设来提出以下代码:
- 文件将上传到特定于登录用户的 Firebase 存储区域。 (例如“userFiles/CURRENT_USER/...”)
- 有关上传文件的信息保存在用户自己的数据下。 (例如“users/CURRENT_USER/uploads/...”
- 每个文件的
title 和detail 属性都会发生变化。这些属性的来源尚不清楚,所以我只是假设它们是通过对象metadata 传入的。
下面的代码应该足以让您开始找出自己的解决方案。
// the array of File objects to upload
const fileObjArray = [ ... ]
// the metadata to store with each file
const metadata = { ... }
// the current user's ID
const currentUserId = firebase.auth().currentUser.uid;
// Where to save information about the uploads
const databaseRef = firebase.database().ref("user").child(currentUserId).child('uploads');
// Create an ID for this set of uploaded files
const uploadId = storageRef.push().key;
// Save files to storage in a subfolder of the user's files corresponding to the uploadId
const storageRef = firebase.storage().ref("userFiles").child(currentUserId).child(uploadId);
// Upload each file in fileObjArray, then fetch their download URLs and then return an object containing information about the uploaded file
var uploadPromiseArray = fileObjArray.map((fileObj) => {
var uploadTask = storageRef.child(fileObj.name).put(fileObj, metadata)
return uploadTask.then(uploadSnapshot => {
// file uploaded successfully. Fetch url for the file and return it along with the UploadTaskSnapshot
return uploadSnapshot.ref.getDownloadURL().then((url) => {
return {
downloadUrl: url,
snapshot: uploadSnapshot
};
});
});
});
// uploadPromiseArray is an array of Promises that resolve as objects with the properties "downloadUrl" and "snapshot"
Promise.all(uploadPromiseArray)
.then((uploadResultArray) => {
var batchUploadData = {
timestamp: firebase.database.ServerValue.TIMESTAMP, // use the server's time
files: [],
... // other upload metadata such as reason, expiry, permissions, etc.
}
batchUploadData.files = uploadResultArray.map((uploadResult) => {
// rearrange the file's snapshot data and downloadUrl for storing in the database
return {
file: uploadResult.snapshot.name,
url: uploadResult.url,
title: uploadResult.snapshot.metadata.customMetadata.title,
detail: uploadResult.snapshot.metadata.customMetadata.detail
};
});
// commit the data about this upload to the database.
return databaseRef.child(uploadId).set(batchUploadData);
})
.then((dataSnapshot) => {
// the upload completed and information about the upload was saved to the database successfully
// TODO: do something
}, (err) => {
// some error occured
// - a file upload failed/was cancelled
// - the database write failed
// - permission error from Storage or Realtime Database
// TODO: handle error
});
// Warning: this line will be reached before the above code has finished executing
这是它在数据库上的样子:
"users": {
"someUserId-78sda9823": {
"email": "example@example.com",
"name": "mr-example",
"username": "mrexemplary",
"uploads": {
"niase89f73oui2kqwnas98azsa": {
"timestamp": 1554890267823,
"files": {
"1": {
"file": "somefile.pdf",
"url": "https://firebasestorage.googleapis.com/v0/b/bucket/o/userFiles%2FsomeUserId-78sda9823%2Fsomefile.pdf",
"title": "Some File",
"detail": "Contains a report about some stuff"
},
"2": {
"file": "screenshot.png",
"url": "https://firebasestorage.googleapis.com/v0/b/bucket/o/userFiles%2FsomeUserId-78sda9823%2Fscreenshot.png",
"title": "Screenshot of problem",
"detail": "Contains an image that shows some stuff"
},
...
}
},
...
},
...
},
...
}
注意 1:此代码尚未完成。它缺少对权限错误和不完整文件上传等问题的错误处理。这是你要解决的问题。
注意2:对于不完整的文件上传,如果有文件上传失败或下载地址成功,则不会写入数据库。解决此问题的一种可能方法是将catch 添加到uploadTask,在错误时返回null,然后在uploadResultArray.map(...) 步骤中跳过任何为空的uploadResult 变量或写入失败的数据库对于那个特定的文件。
注意 3:因为 Firebase 存储和实时数据库都使用快照,所以在您的代码中同时使用它们时,尽量将它们分别称为 uploadSnapshot/fileSnapshot 和 dataSnapshot,以尽量减少混淆.同样,将您的参考文献命名为 somethingStorageRef/somethingSRef 和 somethingDatabaseRef/somethingDBRef。