动态添加图像 next js 14

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

我有一个管理面板,可以在其中添加产品图像。这是允许我执行此操作的操作:

export const createProduct = async (state, formData) => {
  const result = productSchema.safeParse(
    Object.fromEntries(formData.entries())
  );

  console.log(result.error);

  if (result.success === false) return result.error.formErrors.fieldErrors;

  const {
    title,
    vendorCode,
    image,
    categoryId,
    characteristics,
    mainCategoryId,
    price,
  } = result.data;

  const data = result.data;
  await fs.mkdir("public/products", { recursive: true });
  const imagePath = `/products/${crypto.randomUUID()}-${data.image.name}`;
  await fs.writeFile(
    `public${imagePath}`,
    Buffer.from(await data.image.arrayBuffer())
  );

  const product = await db.product.create({
    data: {
      title,
      slug: slugify(`${title}-${vendorCode}`, {
        locale: "ru",
        lower: true,
      }),
      image: imagePath,
      categoryId,
      vendorCode,
      mainCategoryId,
      price,
    },
  });

  await db.productCharacteristic.createMany({
    data: characteristics.map((char) => ({
      title: char.title,
      variants: char.values.map(({ value }) => value),
      productId: product.id,
    })),
  });
  revalidatePath("/");
  redirect("/admin/catalog");

这个例子展示了我如何使用产品图片:

<Image
  className="absolute top-0 left-0 w-full h-full object-cover"
  src={product.image}
  width={800}
  height={800}
  alt={product.title}
/>

在开发模式下工作正常,但在生产模式下我的云托管上出现问题。图像取自 /_next/image 文件夹。在管理员中添加新产品时,图像不会转到 /_next/image 直到您执行 npm run build

如何解决此问题,以便在添加新产品时,图像进入此文件夹并显示在网站上?

我尝试使用minimumCacheTTL,但没有成功

/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
  env: {
    SERVER_URL: process.env.SERVER_URL,
  },
  images: {
    minimumCacheTTL: 60,
  },
};

export default nextConfig;
next.js next.js14 app-router
1个回答
0
投票

根据文档:

  • 只有在构建时位于公共目录中的资产才会由 Next.js 提供服务。在请求时添加的文件将不可用。我们建议使用 Vercel Blob 等第三方服务 用于持久文件存储。

换句话说,Next.js 不应该提供动态资产的存储。

https://nextjs.org/docs/app/building-your-application/optimizing/static-assets

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