Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is:

API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests.

The front end includes an input that can accept multiple files (mainly images), which are then stored in event.target.files.

A function saves each file in a state array, and on submit, it sends a post request to the next.js API.

Front-end logic:

The handleListingPhotos function automatically adds photos to the listingPhotos state when uploaded:

const handleListingPhotos = async (e: any) => {
    setMessage(null);
    let file = e.target.files;

    console.log("hello", file);

    for (let i = 0; i < file.length; i++) {
      const fileType = file[i]["type"];
      const validImageTypes = ["image/jpeg", "image/png"];
      if (validImageTypes.includes(fileType)) {
        setListingPhotos((prev: any) => {
          return [...prev, file[i]];
        });
      } else {
        setMessage("Only images are accepted");
      }
    }
  };

Once the photos are stored, their data can be viewed in the browser's console.log. When onSubmit triggers the POST API:

const handleSubmit = async (e: any) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("files[]", listingPhotos);
    await fetch(`/api/upload/uploadPhoto`, {
      method: "POST",
      headers: { "Content-Type": "multipart/form-data" },
      body: formData,
    }).then((res) => res.json());
  };
  console.log("listingphotos:", listingPhotos);

However, the issue arises when logging req.body in the S3 Bucket upload process, showing information like:

req.body ------WebKitFormBoundarydsKofVokaJRIbco1
Content-Disposition: form-data; name="files[]"

[object File][object File][object File][object File]
------WebKitFormBoundarydsKofVokaJRIbco1--

api/upload/UploadPhoto logic:

import { NextApiRequest, NextApiResponse } from "next";
const AWS = require("aws-sdk");

const access = {
  accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
};

// creates an S3 Client
const s3 = new AWS.S3({ region: "region", credentials: access });

export default async function uploadPhoto(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // take info from parent page
  // console.log("req.body: ", req.body);

  if (req.method === "POST") {
    console.log("req.body", req.body);
    let body = req.body;
    let headers = req.headers;
    let contentType = headers["Content-Type"] || headers["content-type"];

    // check for correct content-type
    if (!contentType.startsWith("multipart/form-data")) {
      return { statusCode: 400, body: "Invalid content type" };
    }

    let boundary = contentType.replace("multipart/form-data; boundary=", "");
    let parts = body.split(boundary);

    for (let part of parts) {
      if (part.startsWith("Content-Disposition")) {
        let [fileData] = part.split("\r\n\r\n");
        fileData = fileData.slice(0, -2);
        let [fileName] = part.split("filename=");
        fileName = fileName.slice(1, -1);
        let params = {
          Bucket: "RANDOM BUCKET NAME",
          Key: fileName,
          Body: fileData,
          ContentType: { "image/png": "image/jpg" },
        };
        // Need to set the PARAMS for the upload
        await s3.putObject(params);
        console.log(
          "Successfully uploaded object: " + params.Bucket + "/" + params.Key
        );
      }
    }
    return {
      statusCode: 200,
      body: "File uploaded",
    };
    // Uploads the files to S3
  }
}

Answer №1

After some experimentation, I managed to develop a method to verify the correct display of the files.

req.body {
  fileName: 'b699417375e46286e5a30fc252b9b5eb.png',
  fileType: 'image/png'
}

The code for the POST request has been revised as follows:

const s3Promises = Array.from(listingPhotos).map(async (file) => {
      const signedUrlRes = await fetch(`/api/upload/uploadPhoto`, {
        method: "POST",
        body: JSON.stringify({
          fileName: file.name,
          fileType: file.type,
        }),
        headers: { "Content-Type": "application/json" },
      });

While this progress is encouraging, there are still challenges ahead, particularly in handling CORS to confirm successful file transfer to the bucket.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

Leveraging an external script for enhanced functionality in React/Meteor application

I'm currently facing a challenge incorporating an external script into my React component within Meteor. I've experimented with directly placing the script tag in my component as follows: TheLounge = React.createClass({ render() { return ( ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

Performance of Nested Menus: A Technological Perspective

In an effort to condense a long stay, the marketing team is requesting our entire sitemap of 5000 pages be accessible through one menu. Despite a year of resistance, we have come to accept that this is inevitable and are now exploring potential technologie ...

Obtain user input and showcase it on the screen using a combination of Ajax and PHP

Whenever a user inputs a value in the textbox, it should dynamically display on the screen. I have successfully implemented this feature once, but I am encountering difficulties with implementing it for a second input. Your help is greatly appreciated. fu ...

Sending data from express js to a different server

Currently, I am faced with a scenario where I need to send a file from Jquery to my Express server and then transfer that request to another server without parsing the file in the Express server. Below are the code snippets I have been using so far: Jquery ...

What happens when you click and trigger mouseleave?

window.onload = function() { $(".compartir").hover(function() { console.log('hover'); var self = this; setTimeout($(self).addClass('ready'), 500); }, function() { var self = this; console.log('leave'); ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

Looking to dynamically update a date variable based on user selection from a drop-down menu in PHP

I am currently working with a PHP file (index.php) which features a title bar displaying the date in the format (MM YYYY). The dates themselves are extracted from another PHP file named latest_update.php. Within the latest_update file, the dates are specif ...

Avoid having individual words centered on a single line of text

Currently, I'm in the process of developing a website using WooCommerce, WordPress, and Elementor. I've encountered an issue where only one word appears on each line and have tried various solutions such as hyphens, word-break, and line-break wit ...

Concentrate on the disappeared div element following the AJAX request

Encountering an unusual issue here that has me a bit puzzled. In one of my DIV elements, I have included several links which trigger an AJAX call (using jQuery) upon being clicked. The server (Controller) then responds with HTML content, specifically a JS ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

Storing and retrieving text in a file using JavaScript: A step-by-step guide

I have a command set up where if a user is mentioned, the discord bot will save the mentioned user's name in a file (I'm utilizing discord.js and node.js). Below is my code snippet: const prv = require('C:/Users/Kikkiu/Desktop/prova.txt&apo ...

What is the best way to integrate a condition for handling invalid or empty input in a Contact Form when using FormSpree?

Utilizing Formspree to create a basic Contact form on my NextJS site. Formspree offers this React code sample: // Don't forget to execute npm install @formspree/react // For additional assistance, go to https://formspr.ee/react-help import React from ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Tips for preventing 404 errors in react-router

I am currently working on a project using React Router and created it using create-react-app. Everything runs smoothly on my local server with links like localhost:3000/login and localhost:3000/product. However, when I deployed the project to my domain, ...

Struggling to maintain data consistency among controllers in Angular by utilizing the rootScope, only to encounter persistent issues with

I am facing an issue with displaying the admin status at the top of all pages for a user who successfully logs in as an admin. Here is my code snippet: <!-- nav bar --> <div> <span ng-show="$root.isAdmin">(ADMIN)</span> </di ...

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

`The universal functionality of body background blur is inconsistent and needs improvement.`

I've developed a modal that blurs the background when the modal window is opened. It's functioning flawlessly with one set of HTML codes, but encountering issues with another set of HTML codes (which seems odd considering the identical CSS and Ja ...

Error message: "document is not defined" thrown by react-icons module in next.js application

I recently encountered an issue while trying to utilize the react-icons module, as it was causing a reference error for me. To install the module, I used the command yarn add react-icons. Here are the specifics: wait - compiling /_error (client and ser ...