我正在用 NodeJS 开发一种 API。
我需要做一种getImage,将与名称对应的图像返回到url(例如:localhost:8080/getImage/myImg)。
我在互联网上找到了很多教程,但问题是我不能使用 FS 的 writeFile 和 readFile,因为我的图像存储在一个包含其他 JSON 信息的数组中。我存储的图像是由 tomCat 中的另一个 API 发送的,我的工作是通过设置 NodeJS API 来限制对 tomCat API 的调用。
我的问题是如何发送存储到变量/数组/json 中的图像?
我尝试了下面的代码,但是当我要去 localhost:8080/getImage/myImg 时,代码被执行,但没有返回任何内容。我没有尝试使用一种 tmp 文件夹来存储图像,因为我正在开发一个大型产品,如果我可以限制对磁盘的访问,那就太好了。
app.get('/getImage/:name', (req, res) => {
imagesArray.forEach( (image) => {
if(req.params.name === image.small_image_name) {
res.writeHead(200, {'content-type': 'image/jpeg'})
res.end(image.small_image, 'binary')
} else if (req.params.name === image.full_image_name) {
res.writeHead(200, {'content-type': 'image/jpeg'})
res.end(image.full_image, 'binary')
}
})
})
我要做的是:您使用图像名称作为参数对 url 进行 http 请求,以“下载”图像并更改在我的主页上显示的元素的背景。
感谢您未来的回答。祝你今天过得愉快 !