【发布时间】:2020-10-31 21:28:32
【问题描述】:
我正在尝试在我正在制作的聊天网络应用程序上显示和图像。文件(图像)正在上传到 firebase 存储,但未显示。显示消息的功能适用于常规文本
但由于某种原因,图像不是。上传完成后,我可以得到 downloadUrl 但它不显示。我有三个文件messageForm、FileModal。
这是 FileModal 的代码:
addFile = event => {
const file = event.target.files[0];
if (file) {
this.setState({ file });
}
}
sendFile = () => {
const { file } = this.state;
const { uploadFile, closeModal } = this.props;
if (file !== null) {
if (this.isAuthorized(file.name)) {
const metadata = { contentType: mime.lookup(file.name) };
uploadFile(file, metadata);
closeModal();
this.clearFile();
}
}
}
isAuthorized = filename => this.state.authorized.includes(mime.lookup(filename));
clearFile = () => this.setState({ file: null })
render() {
const { modal, closeModal } = this.props;
return (
<Modal basic open={modal} onClose={closeModal}>
<Modal.Header>Select an image file</Modal.Header>
<Modal.Content>
<Input
fluid
label="file Types: JPG, PNG"
onChange={this.addFile}
name="file"
type="file"
/>
</Modal.Content>
<Modal.Actions>
<Button
color="green"
inverted
onClick={this.sendFile}
>
<Icon name={"checkmark"} /> Send
</Button>
<Button
color="red"
inverted
onClick={closeModal}
>
<Icon name={"remove"} /> Cancel
</Button>
</Modal.Actions>
</Modal>
);
}}
这是 messageForm 的代码
uploadFile = (file, metadata) => {
const pathToUpload = this.state.channel.id;
const ref = this.props.messagesRef;
const filePath = `chat/public/${file.name}`;
this.setState({
uploadState: 'uploading',
uploadTask: this.state.storageRef.child(filePath).put(file, metadata)
},
() =>{
// progesss function
this.state.uploadTask.on('state_changed', snap => {
const percentUploaded = Math.round((snap.bytesTransferred / snap.totalBytes) * 100)
this.setState({ percentUploaded })
},
err => {
//error function
console.error(err);
this.setState({
errors: this.state.errors.concat(err),
uploadState: 'error',
uploadTask: null
})
},
() => {
// on complete upload function, that is waht to do when it has upload to the database
this.state.uploadTask.snapshot.ref.getDownloadURL().then(downloadUrl => {
console.log(downloadUrl);
this.sendFileMessage(downloadUrl, ref, filePath)
})
.catch(err => {
console.error(err);
this.setState({
errors: this.state.errors.concat(err),
uploadState: 'error',
uploadTask: null
})
})
}
)
}
)
}
sendFileMessage = (fileUrl, ref, pathToUpload) => {
ref
.child(pathToUpload)
.push()
.set(this.createMessage(fileUrl))
.then(() => {
this.setState({ uploadState: "done" });
})
.catch(err => {
console.error(err);
this.setState({
errors: this.state.errors.concat(err)
});
});
};
【问题讨论】:
标签: javascript reactjs firebase google-cloud-storage