[英]To see JPG file from API gateway and Lambda
I created some code on lambda using node.我使用 node 在 lambda 上创建了一些代码。
const fs= require('fs');
const axios= require('axios');
exports.handler= async (event, context, callback) => {
const imageBase64= await axios.get(
'https://upload.wikimedia.org/wikipedia/commons/8/84/Prunus_flower.jpg',
{responseType: 'arraybuffer'}
).toString('base64');
return {
statusCode: 200,
headers: { 'Content-Type': 'image/jpeg' },
body: imageBase64,
isBase64Encoded: true,
}
}
I also set up API gateway.我还设置了 API 网关。
Binary Media Types is image/*
二进制媒体类型是
image/*
Then, when I access API gateway.然后,当我访问 API 网关时。 I encountered bellow error.
我遇到了以下错误。
https://p9knlxmx62.execute-api.ap-northeast-1.amazonaws.com/img/ https://p9knlxmx62.execute-api.ap-northeast-1.amazonaws.com/img/
I'm not sure how can I fix this.我不知道我该如何解决这个问题。
Your imageBase64
is not a valid image Base64 string.您的
imageBase64
不是有效的图像 Base64 字符串。
To get a image file form url and transfer to base64 string with axios
, you can see my code:要获取图像文件表单 url 并使用
axios
传输到 base64 字符串,您可以看到我的代码:
...
const response = await axios.get(
'https://upload.wikimedia.org/wikipedia/commons/8/84/Prunus_flower.jpg',
{ responseType: 'arraybuffer' }
);
const imageBase64 = Buffer.from(response.data, 'binary').toString('base64');
...
1) You've to call callback. 1)您必须调用回调。
2) Result of axios call is object where image is in .data
2) axios 调用的结果是图像在
.data
对象
So overall handler code:所以整体处理程序代码:
exports.handler= async (event, context, callback) => {
const imageBody = await axios.get(
'https://upload.wikimedia.org/wikipedia/commons/8/84/Prunus_flower.jpg',
{responseType: 'arraybuffer'}
);
callback(null, {
statusCode: 200,
headers: { 'Content-Type': 'image/jpeg' },
body: imageBody.data.toString('base64'),
isBase64Encoded: true,
}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.