Next.js 动态添加图片+客户端引用

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

在 /public/ 我有一个名为 /public/cms_images 的文件夹。

每当用户使用我们创建的管理门户上传图像时,cms_images 就会被填充(与 next.js 项目、其 asp.net 分开,只是将图像放入我的 next.js 项目的文件夹中)

在 /pageThatUsesImage.js 上,如果我构建应用程序并为其提供服务(下一个构建 && 下一个启动),页面将工作并引用图像

但是当添加新图像时,图像会抛出 404

我通过客户端 API 调用引用图像的文件名 + 文件类型。

<img src={`/cms_images/` + dataFromPageAPI.imageFileName} />
是否有任何解决办法可以让动态添加的图像在运行时显示?

reactjs image dynamic next.js filepath
1个回答
0
投票
我在使用“next/image”加载图像时遇到了类似的问题(

https://nextjs.org/docs/pages/api-reference/components/image)。我的后端在“/api”上运行,但需要使用完整的 url 引用源。以下解决了它:

// image.component.tsx import { default as NextImage, ImageProps } from "next/image"; export const backendUrl = (src: string) => { const isServerSided = typeof window === "undefined"; return isServerSided ? `${process.env.NEXT_PUBLIC_URL_SELF}/api${src}` : `${window.origin}/api${src}`; }; export const Image = (props: ImageProps) => { if (typeof props.src !== "string") { return; } return <NextImage {...props} src={backendUrl(props.src)} />; };
您需要在环境变量中定义“NEXT_PUBLIC_URL_SELF”

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables

这里的好处是:

    您可以在服务器端和客户端使用新的图像组件
  • 内置图像优化(给出宽度和高度)功能
  • 如果您通过不同阶段(开发、测试、生产)部署应用程序,这将有效
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.