如何使用nextjs版本14动态添加图像

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

我构建了一个管理面板,您可以在其中为项目添加图像。下面的 JavaScript 代码是帮助我做到这一点的操作。

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

我的问题是,如何让图像进入

/_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;
image next.js next.js14 app-router
1个回答
0
投票

根据文档

  • 只有在构建时位于公共目录中的资产才会由 Next.js 提供服务。在请求时添加的文件将不可用。我们建议使用 Vercel Blob 等第三方服务 用于持久文件存储。
换句话说,Next.js 不应该提供动态资产的存储和服务。您应该使用其他服务来保留它们。

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