Next.js Discord

Discord Forum

Upload Files in NextJs Page Router

Unanswered
Atlantic salmon posted this in #help-forum
Open in Discord
Atlantic salmonOP
I have a requirement to upload a file to s3. I have created an api and I am calling the api from the client side. I am using formData to send the file to server side where I will upload the image to s3.
The problem I am getting is in the server side function to read the data sent from the request body.
I saw a few methods like using Server Actions or using req.formData() but these are available in app router where as my project is based on page router with Next13
This below is my server side api
export async function uploadObjectToS3(req: any, res: any) {

  try {
    console.log("Api Called ", req.body);
    
    const { bucket, key, contentType } = req.body;
    const file = req.file;

    if (!bucket || !key || !file) {
      return res.status(400).send({ message: 'Bucket name, object name, and file are required' });
    }
    
    const params = {
      Bucket: bucket,
      Key: key,
      Body: Readable.from(file.buffer),
      ContentType: contentType,
    };
    
    // Upload the file to S3.
    const data = await s3.upload(params).promise();

    console.log(`File uploaded successfully ${data.Location}`);
    return res.status(201).json({ location: "data.Location" });
  } catch (error: any) {
    console.error('Error uploading file:', error);
    return res.status(500).send({ message: 'Error uploading file', error });
  }
}

1 Reply

Atlantic salmonOP
And this is my client side code
  const handleUpload = async () => {
    if (!fileType || !selectedFile) {
      toast({
        title: 'Incomplete form',
        description: 'Please select a type and choose a file to upload.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      return;
    }
    let bucket_name: string = '';
    if (pagesApiData && pagesApiData[0]?.StoreWeb?.domain_name) {
      bucket_name = pagesApiData[0]?.StoreWeb?.domain_name ?? '';
    }
    const params = {
      Bucket: bucket_name,
      Key: `${selectedFile.name}`,
      file: selectedFile,
      ContentType: selectedFile.type,
    };
    try {
      const formData = new FormData();
      formData.set('file', selectedFile);
      formData.set('bucket', bucket_name);
      formData.set('key', selectedFile.name);
      formData.set('ContentType', selectedFile.type);

      const url = `${process.env.NEXT_PUBLIC_BASE_URL}/api/s3-url/put-object`;
      return await fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type':'multipart/form-data',
        }
      }).then((response) => response.json());
    } catch (error: any) {
      console.log(error.message);
      console.error('Error uploading file:', error);
    }
  };