问题描述
我正在尝试在我正在制作的聊天Web应用程序上显示和成像。该文件(图像)已上传到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),uploadTask: null
})
})
}
)
}
)
}
sendFileMessage = (fileUrl,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)
});
});
};
解决方法
如错误所述,您的路径值不能为空字符串或不能包含诸如“.”,“#”,“$”,“[”,or “]”
之类的值。我建议您仔细检查这些变量的值,并确保它们是有效路径:
-
pathToUpload
-
filePath