我正在通过Firebase Web应用程序使用Redux Saga,我需要获取我上传的文件的下载URL,然后在Firestore中创建一个文档(包含有关该文件的更多元数据,例如名称,文档类型等) 。
我如何使用Redux Saga上传文件,然后获取下载URL并在Building子集合中创建文档?
这是我到目前为止所拥有的:
export function* createBuildingDocAsync({ payload: values }) {
// docFile contains meta info about file
const docFile = values.docFile;
// building doc has sub-collection of documents/files
const buildingId = values.buildingId;
try {
const createdAt = new Date();
const buildingsCollection = firestore.collection('buildings');
const documentRef = buildingsCollection.doc(buildingId).collection('documents');
const storageRef = firebase.storage().ref();
const fileRef = storageRef.child('buildings/documents/'+buildingId+"/"+docFile.name);
// upload the file
let uploadTask = yield fileRef.put(docFile);
// Use download url and create document in subcollection
yield documentRef.add({
...docFile,
fileUrl: downloadUrlGoesHere,
createdAt,
});
} catch (error) {
console.log(error);
toastr.error('Error!', 'Please try again');
}
}
任何帮助将不胜感激!
干杯!
以防万一有人在这方面也很挣扎,这是我的解决方案:
export function* createBuildingDocAsync({ payload: values }) {
const docFile = values.docFile;
const buildingId = values.buildingId;
try {
const createdAt = new Date();
const buildingsCollection = firestore.collection('buildings');
const documentRef = buildingsCollection.doc(buildingId).collection('documents');
const storageRef = firebaseStorage.ref();
const fileRef = storageRef.child('buildings/documents/'+buildingId+"/"+docFile.name);
yield fileRef.put(docFile);
const downloadUrl = yield fileRef.getDownloadURL();
const createdDocument = yield documentRef.add({
...values.docData,
fileUrl: downloadUrl,
createdAt,
});
const documentReference = yield documentRef.doc(createdDocument.id).get();
/// do more stuff ///
} catch (error) {
yield put(buildingDocumentUploadFailure(error.message));
toastr.error('Error!', 'Please try again');
}
}
我尝试制作文件的进度条,但是当进度达到100时,我得到了错误的链接,为什么会发生这种情况,有人知道如何在redux-saga中执行此操作吗?请帮助我,我不明白为什么如果我上传的文件大小超过600kb,我会得到不正确的链接
function* avatarUpload(action) {
const { image, uid } = action.payload;
// eslint-disable-next-line no-unused-vars
const metadata = {
contentType: image.type,
};
const fileRef = storageRef.child(`avatars/${uid}`);
const ref = fileRef.put(image);
const channel = eventChannel(emit => ref.on('state_changed', emit));
while (true) {
try {
const snapshot = yield take(channel);
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(progress);
if (progress === 100) {
const downloadUrl = yield fileRef.getDownloadURL();
console.log(downloadUrl);
}
} catch (e) {
console.log(e);
}
}
}