Sending an array of files with JSON through axios: A guide

Working on a React project with TypeScript and Axios, I am faced with the challenge of sending an array of images to the server. Can this be achieved using JSON instead of FormData? Upon setting the array named images, the files received on the server are as follows:

https://i.sstatic.net/r8Cgx.png

However, when attempting to retrieve the array named images, it returns undefined. Is there a way to post a file array using JSON?

The code snippet for my POST request is shown below:

export const createProduct = async (product: IProductCreate) => {
  const { data } = await $authHost.post<IProductCreate>('api/product', product, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return data
}

await createProduct({
      description,
      price,
      gender: JSON.stringify(gender),
      images: images,
      Colors: JSON.stringify(colors),
      BrandId,
      CategoryId
    })

For the backend operations, I am using Express with Sequelize in TypeScript. The code for handling file upload within the create method is outlined below:

async create (req: productCreateRequest, res: Response, next: NextFunction): Promise<void> {
    try {
      ...
      if (!req.files) return next(ApiError.internal('Images are not uploaded'))
      const { images } = req.files // get images.0, images.1, images.2 (for each element or a file array)

      const fileNames: string[] = []
      if (Array.isArray(images)) {
        images.forEach((el, index) => {
          fileNames[index] = uuidv4() + '.png'
          el.mv(path.resolve('src/static/' + fileNames[index]))
        })
      } else {
        fileNames[0] = uuidv4() + '.png'
        images.mv(path.resolve('src/static/' + fileNames[0]))
      }

      const product = await Product.create({
        CategoryId,
        BrandId,
        price,
        description,
        gender: JSON.stringify(parsedGender),
        images: JSON.stringify(fileNames)
      })

      res.json(product)
    } catch (error) {
      ...
    }
  }

Answer №1

To successfully transfer the files, consider converting them to binary format before sending. Utilize the following method for each individual file:

documents.docx.data.toString('binary')

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

What could be causing issues with my Angular and Express.js Server-Sent Events implementation?

Objective: Implement Server-Sent Events in Angular App with Express Backend Issue: Client does not receive Server-Sent Events Backend Implementation router.get('/options/:a/:b/:c', async (req, res) => { console.log('options endpoint c ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...

What is the best way to eliminate a mistaken error in TypeScript (specifically error: TS2339)?

var out = document.getElementsByClassName('myclass')[0]; out.focus(); out.select(); out.selectionStart =1; I've encountered an issue in my TypeScript file while attempting to execute the above code. Unfortunately, it's throwing errors ...

steps to incorporate highcharts offline-exporting in typescript

I've tried the configurations below but they are not working as expected. import * as Highcharts from 'highcharts/highstock'; /*import * as HighchartsExporting from 'highcharts/modules/exporting'; HighchartsExporting(Highcharts);* ...

WebStorm experiencing issues with Express

I've encountered an issue while attempting to set up an Express project using WebStorm. The error message I received is as follows: error creating Node.js Express App. Time limit exceeded for command: "C:\Program Files\nodejs\node.exe" ...

Error in MongoDB Connection: Timeout issue caused by an unresolved Promise

Issue Overview Whenever I attempt to execute nodemon server, a timeout error is displayed indicating [nodemon] app crashed - waiting for file changes before starting.... Detailed Problem Description I have three files located at the following paths: ...

Attempting to extract information from an API and then seamlessly render it onto a different component within a React application

I'm currently working on mapping an array of movies obtained from an API request. Even though the data is successfully fetched, I encounter an issue where the values become undefined when I try to map and display them. As a newcomer to React, I woul ...

"Can anyone explain why my plugin is displaying the error message 'Definition for rule was not found'

Introducing my custom plugin You can find the plugin here: @bluelovers/eslint-plugin For the base config, visit: https://github.com/bluelovers/ws-node-bluelovers/blob/master/packages/eslintrc/.eslintrc.json When it comes to the runtime user config: { ...

How can I create signed URLs for a list of file names?

Currently, I have a setup where my Node / Express backend is fetching files from a secure GCS bucket using the .getFiles() method. The process involves looping through an array of filenames, generating signed URLs for each file, obtaining dimensions using ...

Encountering an issue with the ternary operation: Receiving the error message "Expected 0 arguments, but received

Encountering an issue in this function: prepareTickerIn(value: any){ let valueToReturn = ''; value.map((item,i,arr) => { valueToReturn += (arr.length-1 == i) ? (i==0 ? item.id : 'tickerId.in='+item.id) : ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

Exclusive Vue3 Props that cannot be used together

How can a component be created that accepts either json with jsonParserRules or jsonUrl with jsonParserRulesUrl, but not both? It would be ideal if the IDE could provide a warning when both props are specified. Example of an Attempt that does not Work < ...

The type 'Promise<UserCredential>' cannot be assigned to

import React, {createContext, useContext, useEffect, useState, ReactNode} from "react"; import { auth } from '../utils/init-firebase'; import { createUserWithEmailAndPassword } from "firebase/auth" type ButtonProps = { ch ...

What could be causing the ASP.NET Core 6 MVC Route handler to reject data from an axios post request?

I am looking to send an id to the backend and receive the expected result. Here is the frontend code snippet: import axios from "axios" export async function getList(val) { return await axios.post('http://localhost:5107/PlantsInfo' ...

The function cannot accept a string as an argument, it specifically requires a Blob

Having run into a dilemma here. import React, { useState } from "react"; const PhotoUploader: React.FC = () => { const [photo, setPhoto] = useState(""); let reader = new FileReader(); reader.readAsDataURL(photo); const hand ...

How to Fix TypeScript React JS Lint Error: Missing Dependency in React Hook useEffect without Disabling Lint or Adding Additional Dependencies

As I build a Web application using React JS and TypeScript with React hooks, I encountered a warning when utilizing a custom hook in my Component. The warning states that the dependency 'productsHook' is missing in the useEffect hook. One way to ...

Steps to allow an ng-model to accept a variety of input values

Imagine having an input box structured like this <ion-input [(ngModel)]="Gender" type="text" placeholder="Gender Type"></ion-input> <ion-input [(ngModel)]="hairCat" type="text" placeholder="Hair Type"></ion-input> Now, let's ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

How can we prevent clients from sending the same request multiple times in Mongo&Express?

Exploring the Issue: As I work on developing a liking system similar to Facebook's, where each user can like a post only once, I have encountered a problem that needs attention. In this system, I am using Mongoose and Express on the server-side, alon ...