从Next.JS API返回图像并在浏览器中显示

0sgqnhkj  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(141)

我想向我自己的next.js端点发出请求,并返回一个图像,然后我可以嵌入到我的网站中。现在的问题在我看来,图像是“下载“直接-它不停留在浏览器窗口。

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export const GET = async (_req: NextRequest) => {

  const res = await fetch("https://picsum.photos/200/300");
  const blob = await res.blob();

  const headers = new Headers();

  headers.set("Content-Type", "image/*");
  
  return new NextResponse(blob, { status: 200, statusText: "OK", headers });
};

我如何使用next.js实现它,从API返回的图像在浏览器中呈现(就像转到www.mywebsite.com/myphoto.png这样的URL)

nfg76nw0

nfg76nw01#

您可以返回b64编码的图像(blob),然后在浏览器中显示它。
您的API

export default async function handler(req, res) {
    const img = await fetch("http://localhost:3000/example.jpeg");
    const blob = await img.blob();
    const text = await blob.arrayBuffer();
    res.setHeader("content-Type", "text/plain");
    const encoded = Buffer.from(text).toString("base64");
    res.send(encoded);
}

你的页面

"use client"

import {useState} from "react";

export default function Page() {
    const [image, setImage] = useState(null);
    const displayImage = async () => {
        setImage(await fetch('/api/download').then((res) => res.text()));
    }
  return (<>
      <button onClick={displayImage}>Display image</button>
        {image && <img src={`data:image/jpeg;base64, ${image}`} />}
  </>)
}

相关问题