Search code examples
node.jsreactjsexpressaxiosmulter

Why React doesn't upload image to server?


I have an app using react and express on the backend and multer to manage the upload. The server side is running properly when I make tests using postman, but if trait to send an image from react the result is unexpected. In that case the file doesn't appear in the uploads folder, however with postman is immediatly.

UploadPage,jsx

 const { register, handleSubmit } = useForm();

 const onSubmit = async (data)  => {
        const formData = new FormData();
        formData.append('petimage', data.petimage);
        try {
            const res = await axios.post('/api/petregister', formData);
            console.log(res)
        } catch (error) {
            setError(error.response.data.error);
            setTimeout(() => {
                setError("");
            }, 5000);
        } 
    }
    
    return (
        <Container className="mt-5">
                    <Form onSubmit={handleSubmit(onSubmit)}>
                        <Form.Group controlId="formFile" className="mb-3">
                            <Form.Label>Imagen de tu Mascota</Form.Label>
                            <Form.Control type="file" 
                                label="Select image"
                                name="petimage"
                                 {...register("petimage")}
                            />
                        </Form.Group>
                        <Button variant="primary" type="submit">
                            Submit
                        </Button>
                    </Form>
       </Container>

Google Response

enter image description here

The fields with name petimage are the same that I expecified in the backend and used these in the postman tests.

Edit

const store = require('../middlewares/multer');

route.post('/petregister', store.array('petimage', 12), petregister);

The last section of code is the route that is linked with the multer midleware asigned to ssave the images.


Solution

  • The solution was trait the image as an object. The code is the next:

    Object.values(data.petimage).forEach(pet => formData.append('petimage', pet))
    

    Then it worked as expected.