I have searched for a lot of information on how to upload images as well as information on different inputs, but I cannot understand why the images are not received in NodeJS.
I have a form, in this I have different unputs but to load images I am using react-dropzone, the images that are inside react-dropzone are saved in the state correctly as follows:
DragDrop component
const DragAndDrop = ({files, setFiles, setDropError }) => {
const onDropRejected = () => {
setDropError('Imágenes con tamaño Máximo de 1MB')
setTimeout(() => {
setDropError('')
}, 3000)
}
const {
acceptedFiles,
fileRejections,
getRootProps,
getInputProps
} = useDropzone({
accept: {
'image/jpeg': [],
'image/jpg': [],
'image/png': []
},
maxFiles:3,
maxSize:1000000,
onDropRejected,
onDropAccepted: acceptedFiles => {
setFiles(acceptedFiles.map(file =>
Object.assign(file, {
preview: URL.createObjectURL(file)
})));
}
})
const removeFile = file => () => {
const newFiles = [...files]
newFiles.splice(newFiles.indexOf(file), 1)
setFiles(newFiles)
}
const removeAll = () => {
setFiles([])
}
const thumbs = files.map(file => (
<div key={file.name}>
<button onClick={removeFile(file)} className="text-center hover:bg-blue-200 absolute rounded">
<span className='p-2 text-center text-lg'>x</span>
</button>
<div className='w-32'>
<img
src={file.preview}
// Revoke data uri after image is loaded
onLoad={() => { URL.revokeObjectURL(file.preview) }}
/>
</div>
</div>
))
useEffect(() => {
// Make sure to revoke the data uris to avoid memory leaks, will run on unmount
return () => files.forEach(file => URL.revokeObjectURL(file.preview));
}, []);
const acceptedFileItems = acceptedFiles.map(file => (
<li key={file.path}>
{file.path} - {file.size} bytes
</li>
));
const fileRejectionItems = fileRejections.map(({ file, errors }) => {
return (
<li key={file.path}>
{file.path} - {file.size} bytes
<ul>
{errors.map(e => <li key={e.code}>{e.message}</li>)}
</ul>
</li>
)
});
return (
<section className={`container mt-6`}>
<div {...getRootProps({ className: 'dropzone' })} className={`flex flex-col justify-center border-2 border-cyan-600 border-dashed p-4 cursor-pointer ${ files.length === 3 && 'pointer-events-none' }`}>
<input {...getInputProps()} />
<div className='flex flex-col justify-center text-center gap-2 mb-2'>
<p>Arrastra y suelta imágenes o selecciona dando click</p>
<em className='text-xs'>(Máximo 3 imágenes, .jpg, .png)</em>
</div>
</div>
<aside className='text-xs mt-4'>
{files.length === 3 && <div>{files.length}</div>}
{/* <h4>Archivos Correctos</h4>
<ul>{acceptedFileItems}</ul>
<h4>Archivos con error</h4>
<ul>{fileRejectionItems}</ul> */}
<div className="flex gap-4 justify-center">
{thumbs}
</div>
</aside>
{files.length > 0 && <button onClick={removeAll} className="btn btn-xs text-xs mt-4 btn-ghost">Eliminar</button>}
</section>
);
}
export default DragAndDrop
After imported inside the component where I have the form I show it correctly and the user can choose up to 3 images:
const NewProduct = () => {
const [files, setFiles] = useState([])
const onSubmit = data => {
try {
data.pictures = files // Here I indicate that data.pictures will be equal to the content of my state files
postProduct(data)
} catch (error) {
}
}
return (
<form
onSubmit={handleSubmit(onSubmit)}
className='flex-auto px-4 rounded-b-md md:px-10 py-5 pt-0 border-2 bg-slate-100 shadow-lg'
>
<DragAndDrop
files={files}
setFiles={setFiles}
setDropError={setDropError}
/>
----
So this is sent to make the request from postProduct to Nodejs:

Now, to make the request to NodeJS, I use postProduct, where I pass the form data that already contains the images in data.pictures and use FormData traversing the array of images and setting ‘pictures’
const postProduct = async product => {
try {
const dataOnLs = localStorage.getItem('cmtjs')
const formData = new FormData()
for (let i = 0; i < product.pictures.length; i++) {
formData.append(`pictures`, product.pictures)
}
formData.append('barCode', product.barCode)
formData.append('idProduct', product.idProduct)
formData.append('desc', product.desc)
formData.append('name', product.name)
formData.append('category', product.category)
formData.append('presentation', product.presentation)
formData.append('provider', product.provider)
formData.append('purchasePrice', product.purchasePrice)
formData.append('salePrice', product.salePrice)
const config = {
headers: {
"Content-Type": "multipart/form-data",
apiKey: dataOnLs
}
}
const { data } = await axiosClient.post(`/products`, formData, config )
But when doing a console.log(req.files) from Nodejs it always indicates an empty array.

Within POstProduct I have printed the content of formData in the console and despite the fact that it throws me the ‘pictures’ key, its value is [object File] but in NodeJS it arrives empty:
const formData = new FormData()
for (let i = 0; i < product.pictures.length; i++) {
formData.append(`pictures`, product.pictures)
}
for (var d of formData.entries()) {
console.log(d);
}

So the texts of the form are sent correctly to NodeJS but the images are always received as an empty array. I don’t really understand what’s just going on.