This question is about a problem that happen when i want to save the images multer multiple step form and "react-images-upload" in react; Can you help me?Thanks!!
This is about a multiple step form in react.
Media Step:
export default function Media({ formData, setFormData }) {
const handleChange = (event) => {
setFormData({
...formData,
foto: [event]
});
};
return (
<Grid container spacing={1}>
..
<Grid container item xs={8} spacing={2}>
<div className="container">
<FormControl>
<ImageUploader
withIcon={false}
withPreview={true}
buttonText="Choose images"
onChange={handleChange}
imgExtension={[".jpg", ".gif", ".png", ".gif"]}
maxFileSize={5242880}
/>
</FormControl>
</div>
</Grid>
</Grid>
);
ProductForm file:
function getStepContent(stepIndex) {
switch (stepIndex) {
case 0:
return (
<Basics
formData={formData}
setFormData={setFormData}
/>
);
case 1:
return <Price formData={formData} setFormData={setFormData} />;
case 2:
return <Shipping formData={formData} setFormData={setFormData} />;
case 3:
return (
<Media formData={formData} setFormData={setFormData} />
);
}
}
const [activeStep, setActiveStep] = useState(0);
const steps = getSteps();
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleReset = () => {
setActiveStep(0);
};
const save = () => {
saveProduct(formData, setFormData, handleReset);
};
export async function saveProduct(formData, setFormData, handleReset) {
const foto = formData.foto ;
console.log(foto)
return await axios({
method: "post",
url: `${URL}/api/productos`,
data: formData,
headers: { "content-type": "multipart/form-data" },
})
Backend side (it ' s work except the file upload)
router.post('/',upload.array('foto', 10),this.controlador.saveProducts
);
Here is the console.log(event) image
Thanks very much!
CodePudding user response:
You seem to be treating formData
as a plain object but for posting multipart/form-data
, you should be using a FormData
instance.
First, create formData
as a ref
so it's not recreated for every render. You can also create a function to pass to your components for adding files
// in ProductForm
const formData = useRef(new FormData());
const addFoto = (file) => {
formData.current.append("foto", file);
};
Now you can pass the addFoto
function to your components
<Basics addFoto={addFoto} />
and use it in your Media
component
export default function Media({ addFoto }) {
const handleChange = (file) => {
addFoto(file);
};
// ...
Finally, back in your ProductForm
component, post the data like this
// no custom headers required
axios.post(`${URL}/api/productos`, formData.current);