Image 从NextJS中的API响应渲染图像-只需下载base64文件
我正在做一个新的项目,正在学习。我已将base64中的一个图像保存到MySQL数据库,现在我正在尝试执行GET请求,以便在浏览器中显示图像,而不是下载图像。然而,尽管它尝试下载文件,但该文件只是一个包含base64字符串的文件,而不是实际图像 数据库中的文件如下所示(仅是base64的一个片段) 获取图像的API如下所示:Image 从NextJS中的API响应渲染图像-只需下载base64文件,image,api,base64,next.js,Image,Api,Base64,Next.js,我正在做一个新的项目,正在学习。我已将base64中的一个图像保存到MySQL数据库,现在我正在尝试执行GET请求,以便在浏览器中显示图像,而不是下载图像。然而,尽管它尝试下载文件,但该文件只是一个包含base64字符串的文件,而不是实际图像 数据库中的文件如下所示(仅是base64的一个片段) 获取图像的API如下所示: export default async function handler(req : NextApiRequest, res : NextApiResponse) {
export default async function handler(req : NextApiRequest, res : NextApiResponse) {
const prisma = new PrismaClient()
if (req.method === "GET")
{
const {image_id} = req.query;
const image = await prisma.images.findFirst({
where: {
imageId: parseInt(image_id)
}
});
const decoded = Buffer.from(image.content).toString("base64");
console.log(decoded)
res.status(200).send(decoded);
}
else
{
res.status(405).json(returnAPIErrorObject(405, "Method not supported by API endpoint"));
}
}
我已经修改了next.config.js,以提供包含以下内容的自定义标题响应:
module.exports = {
async headers() {
return [
{
source: '/api/images/:image_id',
headers: [
{
key: 'Content-Type',
value: 'image/png:Base64'
}
]
}
]
}
}
如前所述,当我转到URLhttp://localhost:3000/api/images/4
(4为图像id)它下载包含数据库中base64字符串的文件,而不是在浏览器中显示图像
更新
根据@sean w评论中的链接,它现在尝试显示图像,但没有显示实际图片,而是显示一个带有白色正方形的空白窗口,如下面的屏幕截图所示
我的代码现在如下所示:
const {image_id} = req.query;
const image = await prisma.images.findFirst({
where: {
imageId: parseInt(image_id)
}
});
const decoded = Buffer.from(image.content, 'base64').toString();
let imageContent = decoded.replace(/^data:image\/png;base64,/, '');
console.log(decoded);
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': imageContent.length
});
res.end(imageContent);
下面是一个屏幕截图,显示了页面上实际呈现的内容,而不是我的实际图像
我已经解决了这个问题,而不是从数据库中创建缓冲区,我认为这看起来像Prisma,因为该列是一个blob,但我还是给了我一个缓冲区,我首先从数据库中提取base64字符串并删除数据:image/png;base64,然后从该字符串创建缓冲区,并将其发送给响应:
const {image_id} = req.query;
const image = await prisma.images.findFirst({
where: {
imageId: parseInt(image_id)
}
});
const decoded = image.content.toString().replace("data:image/png;base64,", "");
const imageResp = new Buffer(decoded, "base64");
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': imageResp.length
});
res.end(imageResp);
这可能是几件事-这应该有助于你了解问题的真相-@SeanW谢谢,这似乎有帮助,但现在只是得到一个全黑屏幕和一个白框,而不是实际的图像。我已经用更多的信息更新了我的问题
const {image_id} = req.query;
const image = await prisma.images.findFirst({
where: {
imageId: parseInt(image_id)
}
});
const decoded = image.content.toString().replace("data:image/png;base64,", "");
const imageResp = new Buffer(decoded, "base64");
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': imageResp.length
});
res.end(imageResp);