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) {
...
}
}