Respect's avatar

How Upload and Retrive uploaded files in react Next JS in private folder

  • Hello friends Thanks for Answer
  • if i visited http://localhost:3000/tmp/exmaple-name.png RETURN 404 but file path is correct
  • NOTE : no need to upload files to public folder because it's gobal access - I just need make custom url to get the uploaded files by url like /getfile/{filename} - but steel uploaded folder protected from direct access any HELP Thanls
  • NOTE 2 : I created Test api link for test response of file also return 404 The Test api code at the end (SEMILATE WHEN RETURN IMAGES WITH PRODUCT LIST ALSO RETURN 404
// in client code
"use client";
import { useState } from "react";

const UploadPage = () => {
  const [file, setFile] = useState<File>();

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      if (!file) return;

      try {
        const data = new FormData();
        data.set("file", file);

        const res = await fetch("/api/upload", {
          method: "POST",
          body: data,
        });
        // handle the error
        if (!res.ok) throw new Error(await res.text());
      } catch (e: any) {
        // Handle errors here
        console.error(e);
      }
    };


  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          type="file"
          name="file"
          onChange={(e) => setFile(e.target.files?.[0])}
        />
        <input type="submit" value="Upload" className="bg-red-800 text-white p-5" />
      </form>
    </div>
  );
};

export default UploadPage;

// in api server code

import { writeFile } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'

export async function POST(request: NextRequest) {
    const data = await request.formData()
    const file: File | null = data.get('file') as unknown as File

    if (!file) {
        return NextResponse.json({ success: false })
    }

    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    // With the file data in the buffer, you can do whatever you want with it.
    // For this, we'll just write it to the filesystem in a new location
    const path = `tmp/${file.name}`
    await writeFile(path, buffer)
    console.log(`open ${path} to see the uploaded file`)

    return NextResponse.json({ success: true })
}


** TEST CODE FOR CUSTOM API ROUTE FOR RESPONSE

import { NextRequest, NextResponse } from "next/server";

export const GET = async (req: NextRequest, res: NextResponse) => {

    const filePath = `/uploads/abstract-artwork-logo-linux-wallpaper-d374163633f1709651b1b381ada0e928.jpg`;

    try {
        return NextResponse.json({
            "path": filePath
        });
    } catch (error) {
        console.log(' error ', error);
        throw new Error("field to fetch data");
    }
}

** BROWSER RESPONSE

abstract-artwork-logo-linux-wallpaper-d374163633f1709651b1b381ada0e928.jpg:1 
        
        
       GET http://localhost:3000/uploads/abstract-artwork-logo-linux-wallpaper-d374163633f1709651b1b381ada0e928.jpg 404 (Not Found)
0 likes
0 replies

Please or to participate in this conversation.