我想在firebase中保存一个简单的帖子,但是我没有得到它的图像
现在,我的服务
uploadAndSave(item: any) {
let post = { $key: item.key, title: item.title, description: item.description, url: '', fullPath: '' };
if(post.key) {
this.save(post);
} else {
let storageRef = this.fb.storage().ref();
let basePath = `/posts/${new Date()}`; // Path Where I want to save the image
post.fullPath = basePath + '/' + post.title + '.png';
let uploadTask = storageRef.child(post.fullPath).putString(post.fileToUpload, 'base64');
console.log(uploadTask)
this.db.list(`${this.PATH}/`).push(post);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot) => {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(progress + "% done");
},
(error) => {
console.error(error);
},
() => {
post.url = uploadTask.snapshot.downloadURL;
this.save(post);
});
}
}
private save(post: any) {
return new Promise((resolve, reject) => {
if (post.key) {
this.db.list(this.PATH)
.update(post.key, { title: post.title, description: post.description, url: post.url, fullPath: post.fullPath })
.then(() => resolve())
.catch((e) => reject(e));
console.log(post)
} else {
this.db.list(this.PATH)
.push({ title: post.title, description: post.description, url: post.url, fullPath: post.fullPath })
.then(() => resolve());
}
})
}
这是我的看法与图像,标题和说明,我需要sabe所有这些数据,但有些是错误的
<img [src]="imageUrl" alt="" id="image-post">
<input type="file" accept="image/*" (change)="handleFileInput($event.target.files)">
<button type="submit" class="waves-effect teal lighten-1 btn" [disabled]="!form.valid" (click)="createPost()">CRIAR</button>
<a routerLink="/painel/postagens" class="waves-effect red darken-1 btn">CANCELAR</a>
现在这是我的组件
createPost() {
if(this.form.valid)
this.service.uploadAndSave(this.form.value)
.then(() => {
swal("Postagem criada!", "Esta postagem foi inserido no Banco de Dados com sucesso!", "success");
})
.catch((e) => {
swal("Não foi possível salvar a postagem!");
console.error(e);
});
}
handleFileInput(file: FileList) {
this.fileUpload = file.item(0);
if (this.fileUpload.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (event:any) => {
this.imageUrl = event.target.result;
}
reader.readAsDataURL(this.fileUpload);
} else {
swal('Tipo de arquivo não aceito!');
}
}
如果没有图像,我可以将数据保存在firebase中,但当我尝试使用图像保存时,它会出现错误,对不起,这么多代码是我不知道我在代码的哪一部分出错
1条答案
按热度按时间ktecyv1j1#
你需要在这个函数中上传一个图片,你只是在阅读它。官方文档:
要将文件上载到云存储,首先要创建对文件完整路径的引用,包括文件名:
添加文件元数据:
管理上传:
有关其他参考资料,请参阅以下网站:https://firebase.google.com/docs/storage/web/upload-files