0
votes

I am sending images to a nodeJs server using react native. I have noticed that when i make the request, there is an image file in the request but the response fails saying photos are needed for file upload. The request however works perfectly on postman. Here is a sample of the code. I am using react native image crop picker to select the image.

const choosePhotoFromLibrary = () => {
    ImagePicker.openPicker({
        width: 300,
        height: 400,
        cropping: true,
        // multiple: true,
        multiple: false,
        mediaType: 'photo'
    }).then((image) => {
        setPhotos(image.path)
    }).catch(err => {
        console.log(err);
    })
}

getStoreId()
const createProduct = async () => {
    console.log(typeof photos);
    const data = new FormData()
    data.append('name', productName)
    data.append('description', description)
    data.append('price', price)
    data.append('category', productCategory)
    data.append('sub-category', productSubCategory)
    data.append('condition', productCondition)
    data.append('photos', photos)
    data.append('type', `Women's wear`)

    console.log(data);
    var config = {
        method: 'post',
        url:url,
        headers: {
            'token': token,
            'Content-Type': 'multipart/form-data'
        },
        data: data
    };
    try {
        const product = await axios(config)
        console.log(product);
    } catch (err) {
        console.log(err.response);
    }
1

1 Answers

0
votes

Instead of

data.append('photos', photos)

write like this

data.append('photos', {
   name: "Example.jpg",
   uri: photos, // This should be something like 'file://...'
   type: "image/jpg" // MIME type of file
})