0

Actually we have site which use dropzone.js for uploading image to the server.

I'm working with react native app and need to replicate dropzone js behavior.

I'm trying to send base64 image but request return Multipart requests must contain at least one part.

 saveImages(images) {
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'X-Requested-With': 'XMLHttpRequest'
        }
    };
    images.forEach(img => {
        let imgFormData = `data:${img.mime};base64,${(img.data)}`;
        let blob = this.dataURItoBlob(imgFormData);
        let formData = new FormData(document.forms[0]);
        formData.append('file', blob);
        axios.post(SAVE_IMAGE_URL, formData, config)
            .then(res => console.log(res))
            .catch(err => {
                console.log(err);
                console.log(err.status);
                console.log(err.code);
            })
    });
}

    dataURItoBlob = (dataURI) => {

        let byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];


        let ia = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], {type:mimeString});
}
Petia Mushinskiy
  • 41
  • 1
  • 1
  • 5

1 Answers1

4

Fixed with react-native-fetch-blob package

    images.forEach(img => {
        RNFetchBlob.fetch('POST', SAVE_IMAGE_URL, {
            'Content-Type': 'multipart/form-data'
        }, [
            // element with property `filename` will be transformed into `file` in form data
            {name: 'file', filename: 'file.png', data: img.data}
        ]).then((resp) => {
            console.log(resp);
            // ...
        }).catch((err) => {
            // ...
        })

    })
Petia Mushinskiy
  • 41
  • 1
  • 1
  • 5