Я пытаюсь отобразить изображение в Reactjs, которое было отправлено с сервера. Обычно пользователь загружает изображение в GridFS при регистрации, и при входе в систему браузер извлекает это изображение и устанавливает его в состояние «profilePicture», чтобы оно могло отображаться в браузере (не уверен, что это лучший способ сделать это). Это). Я знаю, что передаю изображение в интерфейс, потому что могу его скачать - просто не могу понять, как отобразить его в браузере.
Вот мой код:
Код реагирования
constructor(props){
super(props)
this.state = {
profilePicture: ''
}
}
componentDidMount(){
axios.get("/api/users/getProfilePicture", {
responseType: 'blob',
params: {
profilePictureKey: this.props.auth.user.profilePictureKey
}
}).then(res=>{
//Set image state to response image
this.setState({ profilePicture: res.data })
})
}
render(){
return (
<img src={this.state.profilePicture} />
)
}
Код Node.js
router.get("/getProfilePicture", (req, res) => {
gfs.files.findOne({ filename: req.query.profilePictureKey }, (err, file) => {
if (!file || file.length === 0) {
return res.status(404).json({
error: "That File Doesn't Exist"
});
} else {
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
}
});
})