WebDeveloper0315 / inventory-nextjs-antd

This project can manage inventory using Next.js and Ant Design component.
https://inventory-nextjs-antd.vercel.app
13 stars 9 forks source link

After building the project, new uploaded images are not displayed in Next.js #4

Closed WebDeveloper0315 closed 8 months ago

WebDeveloper0315 commented 8 months ago

In this project, I upload the images to manage the inventory. The images are saved in "public/productImage" path. In the developing environment(npm run dev), everything is good, but after building the project (npm run build,npm run start), new uploaded images are not displayed. I have to run the local server and need to upload to local storage.

------------ Before Build, new uploaded images are displayed ------------------------

beforeBuild

------------ After Build, new uploaded images are not displayed ------------------------

afterBuild

Help me for this issue.

WebDeveloper0315 commented 8 months ago

I solved this issue. I added API function to the api/Image as the following.

import * as fs from 'fs';
import * as path from 'path';

export async function GET(request: Request): Promise<Response> {
  if (!process.env.NEXT_PUBLIC_IMAGES_PATH) {
    throw new Error('NEXT_PUBLIC_IMAGES_PATH is not set');
  }

  const url = new URL(request.url);
  const image = url.searchParams.get('key');

  if (image?.trim()) {
    const imagePath = path.join('public', process.env.NEXT_PUBLIC_IMAGES_PATH, `${image}`);

    if (fs.existsSync(imagePath)) {
      const buffer = fs.readFileSync(imagePath);

      return new Response(buffer, {
        headers: {
          'Content-Type': 'image/png',
        },
      });
    } else {
      return new Response('', { status: 404 });
    }
  }

  return new Response('', { status: 400 });
}

image