我正在使用ReactJS,我需要在前端提供一些图片,我不能用以下方式做到这一点
<img alt="" src={process.env.PUBLIC_URL + image + ".png" } />
因为我将提供以特定关键字开头的超过2张图片,所以我在想这样做
dir= '../../public/images/'
files= fs.readdirSync(dir)
for (const file of files) {
if(file.startsWith(keyword))
{
setPictureName(dir+file+ ".png")
}
}
但不幸的是我无法在客户端使用“fs”模块,所以我迷失了,我应该在后端进行处理然后发送这些图片吗?如果还如何做,我很乐意收到其他建议。
假设您在后端使用 Express,只需将文件作为公共或任何您想要的文件夹中的静态文件提供。
app.use('/static', express.static('public'))
然后通过调用 url 来获取文件
http://localhost:3000/{your_image_name}.jpg
在反应前端:
<img src={`http://localhost:3000/images/image1.png`} alt="" />
我希望您已经在节点后端设置了静态文件夹。如果没有:
app.use(express.static('public'));
后端文件夹结构:public > images > image1.png