如何检查Next JS的Public文件夹中是否存在图片

问题描述 投票:0回答:1

我在 Next-JS-13 的公共文件夹中有数千张启用了打字稿的图像。在我们用作

src
组件的
<Image>
之前,有没有办法检查现有图像?

我尝试使用原生 JS,它可以工作,但是在启用 Next-JS + Typescript 的情况下,脚本对我来说太复杂了。 Next-JS 服务器说:

The requested resource is not a valid image for /cars/audi-4.jpg received text/html; charset=utf-8
ImageError: The requested resource is not a valid image.

如何检查现有的/cars/audi-4.jpg?因此,如果不存在,我可以使用另一个默认图像。

typescript next.js file-exists next.js13
1个回答
0
投票

src pp\page.js(Next.js 13 应用程序)

检查流程的嵌入注释

import Image from "next/image";

// Using HEAD method, just check the headers for status code
const isImageFound = async (imageName) => {
  return await fetch(`http://localhost:3000${imageName}`, {
    method: "HEAD",
  });
};

export default async function Home() {
  // default image name assignment
  let imageName = "/default.jpg";

  // this is the image we are looking for, not sure where you ar gonna pick this.
  let anyExistingImage = "/one.jpg";

  // Check the image is exists in public folder, if not take default image to render.
  const result = await isImageFound(anyExistingImage);
  if (result.status === 200) {
    imageName = anyExistingImage;
  }

  return <Image src={imageName} width={300} height={300} />;
}

Next.js 13 应用程序的文件夹结构,包含公共文件夹和 page.js,

我希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.