我想上传图片并在Firestore文档上上传一个字段,以便它存储url的图片。
为此,我有以下代码: 这个是用相机拍照的。
selectImage(): Promise<any> {
return new Promise(resolve => {
let cameraOptions: CameraOptions = {
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true
};
this.camera.getPicture(cameraOptions)
.then((data) => {
this.cameraImage = "data:image/jpeg;base64," + data;
resolve(this.cameraImage);
});
});
}
此人上传图片,然后更新设置URL的文档。
uploadProfilePhoto() {
console.log(this.cameraImage)
if (this.cameraImage != null) {
this.image = 'profilePhoto' + new Date().getTime() + '.jpg';
let storageRef: any;
let parseUpload: any;
storageRef = firebase.storage().ref('profilePhotos/' +
this.image);
parseUpload = storageRef.putString(this.cameraImage,
'data_url');
let ID = firebase.auth().currentUser.uid;
console.log("ID")
console.log(ID);
parseUpload.on('state_changed', (snapshot) => {
// Upload completed successfully, now we can get the
download URL
snapshot.ref.getDownloadURL().then((downloadURL) => {
let profilePhoto = downloadURL
this.firestore.doc(`users/${ID}`).update({
profilePhoto
})
});
})
}
}
当我运行此代码时,它会完美上传图像,但是有时它不会更新文档,我也找不到原因。 我收到此错误:
加载资源失败:服务器响应状态为404
如果我输入错误显示链接,则显示this。
它不只出现1次,每次运行此代码时,该错误就出现3-4次。
答案 0 :(得分:2)
您收到的消息显示“ 404”,通常被理解为HTTP响应代码,表示“未找到”。错误告诉您,当您调用getDownloadURL时,该文件实际上不存在。这是因为您没有等待文件完成上传。
返回storageRef.putString()
时,文件尚未开始上传。您可以从链接的API文档中看到它返回一个UploadTask对象,该对象的工作方式类似于Promise,因为它上面带有then()方法。您需要使用此UploadTask来确定何时完成上传。只有这样,getDownloadURL才能按照您期望的方式工作。