我有一个上传到s3的图像,现在我正在尝试获取文件流并在我的前端显示该图像。我似乎已在后端成功访问了该图像,但在前端显示该图像时一直遇到困难。
从s3获取文件的函数:
getFileStream: function getFileStream(fileKey){
const downloadParams ={
Key: fileKey,
Bucket: bucketName
}
return s3.getObject(downloadParams).createReadStream();
}
post route将图像上载到s3并实现res.send,以便在下载时为文件提供路径:
router.post('/admin/create', upload.single('images'), async(req, res) => {
try{
const file = req.file;
console.log(req.file);
const result = await uploadFile(file);
await unlinkFile(file.path);
console.log(result);
const newItem = await db.query("INSERT INTO collection (title, product, imagekey, price, info) values ($1, $2, $3, $4, $5) RETURNING *", [req.body.title, req.body.product, result.key, req.body.price, req.body.info]);
res.send({imagePath: `/images/${result.key}`})
res.status(201).json({
status: "success",
results: newItem.rows.length,
data:{
newItem: newItem.rows[0]
}
})
}catch(err){
console.log(err);
}
})
获取图像的路径:
router.get("/images/:key", async (req, res) => {
try{
const key = req.params.key;
const readStream = getFileStream(key);
readStream.pipe(res);
}catch(err){
console.log(err);
}
})
上传的每个文件的图像密钥与图像的其余数据一起存储在我的数据库中。我在前端创建了一个函数,将正确的“src”Map到每个图像,以便显示图像。()/图像/${imagekey}”)
const imageURL = (imagekey) =>{
return(`/images/${imagekey}`);
}
return(
<div>
<div className="main-body">
<div className="collection-menu">
{collection && collection.map(item => {
return(
<div className="collection-item">
<ImagesC classes="collection-thumbnail" source={imageURL(item.imagekey)}/>
</div>
</div>
);
})}
</div>
</div>
</div>
)
我的图像组件:
const ImagesC = (props) => {
return(
<div>
<img className={props.classes} src={props.source}/>
</div>
)
}
暂无答案!
目前还没有任何答案,快来回答吧!