файлы, не определенные при загрузке изображений с помощью

#mysql #node.js #reactjs #formidable

#mysql #node.js #reactjs #formidable

Вопрос:

Я загружаю несколько изображений в базу данных(mysql) с помощью react js в качестве интерфейса и node js в качестве бэкенда, который я использую.

мой код переднего плана выглядит так

 const [pName, setProductName] = useState('')  const [pManuName, setManufacturerName] = useState('')  const [pManuBrand, setManufacturerBrand] = useState('') const [selectedFiles, setselectedFiles] = useState([])    

расположение

 lt;Input  id="productname"  name="productname"  type="text"  className="form-control"  required="required"  onChange={(e)=gt;setProductName(e.target.value)}     lt;Input  id="manufacturername"  name="manufacturername"  type="text"  className="form-control"  required="required"  onChange={(e)=gt;setManufacturerName(e.target.value)}  /gt;     lt;Input  id="manufacturerbrand"  name="manufacturerbrand"  type="text"  className="form-control"  required="required"  onChange={(e)=gt;setManufacturerBrand(e.target.value)}  /gt;   lt;Form encType="multipart/form-data"gt;   lt;Dropzone  onDrop={acceptedFiles =gt; {  handleAcceptedFiles(acceptedFiles)  }}  gt;  {({ getRootProps, getInputProps }) =gt; (  lt;div className="dropzone"gt;  lt;div  className="dz-message needsclick"  {...getRootProps()}  gt;  lt;input {...getInputProps()} name="filetoupload" /gt;  lt;div className="dz-message needsclick"gt;  lt;div className="mb-3"gt;  lt;i className="display-4 text-muted bx bxs-cloud-upload" /gt;  lt;/divgt;  lt;h4gt;Drop files here or click to upload.lt;/h4gt;  lt;/divgt;  lt;/divgt;  lt;/divgt;  )}  lt;/Dropzonegt;  lt;/formgt;  

//Функция для обработки файлов

 function handleAcceptedFiles(files) {  files.map(file =gt;  Object.assign(file, {  preview: URL.createObjectURL(file),  formattedSize: formatBytes(file.size)  })  )   setselectedFiles(files)  }  

и моя функция создания продукта

 const createProduct=()=gt;  {      var formD= new FormData()  formD.append('productName',pName)  formD.append('manufacturerName',pManuName)  formD.append('manufacturerBrand',pManuBrand)  formD.append('filetoupload',selectedFiles)     axios.post(process.env.REACT_APP_DATABASEURL "api/create-product",formD).then((res)=gt;{   console.log("Product created")   })  }  

I am using formidable to parse form also I am inserting images into mysql by using last product created such that one product can have multiple images when i parse the form it shows undefined is I log «files» maybe it is due to my wrong way of parsing

here is my controller code

 exports.store =async(req,res)=gt;{      Products.create({  productName:req.body.productName,  manufacturerName:req.body.manufacturerName,  manufacturerBrand:req.body.manufacturerBrand,  price:req.body.price,  category:req.body.category,  features:req.body.features,  productDescription:req.body.productDescription }).then((result)=gt;{      var form = new formidable.IncomingForm() form.parse(req,function(err,fields,files){    console.log(files.filetoupload) //undefined when using formData but doesnt even come here if I pass object in axios request instead of FormData   files.filetoupload.map((row)=gt;{  var oldpath =row.filepath;  console.log(oldpath)  var newpath = '/images/products/'   row.originalFilename;  var fullpath = __dirname '/images/products/'   row.originalFilename;  ProductImages.create({  productId:result.id,  imagePath:newpath,  })  fs.rename(oldpath, fullpath, function (err) {  if (err) throw err;  res.write('File uploaded and moved!');  res.end();  });  })     })   })   }  

I was trying to loop through each file to insert one by one into database and in upload folder but it isnt working

What i have tried Instead of using FormData I have also tried passing object but in that case code inside form.parse function isnt even reaching for example if i display something in console.log it isnt even displayed in this case

where I am wrong and how it can be achieved

 **UPDATE NOTE**  

When I place all fields under one form and dont use axios and just do a normal form submit like in html it works but how will i be able to do it with react setup i mean setting fields usign useState and doing axios request instead of using action attribute in form