Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file from react-native to upload image same as `<input type="file" onChange={this.fileChangedHandler}> `

I have tried doing

var photo = {
    uri: uriFromCameraRoll,
    type: 'image/jpeg',
    name: 'photo.jpg',
};

and using

axios

var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');

const config = {
            headers: {
                'content-Type': 'multipart/form-data'
            }
        }
 MY_API().then(instance => {

// it is axios instance
            instance.post("/api/v1/upload",
                { body }
                , config).then(res => {
                    console.log(JSON.stringify(res));

                }).catch(err => {
                    console.log(err);
                })
        }
        )

On removing config I get

Error 503

and with config it gives

Error: Multipart: Boundary not found

and works fine with POSTMAN also... Along with headers

I have also tried to upload File (blob) , but same error of

Error: Multipart: Boundary not found

 dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

//Usage example:
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt');
console.log(file);

API works well in ReactJS with code enter image description here

EDIT : I have solved the problem by using React-native-fetch-blob, but looking to solve using axios ,

here is the code :

 RNFetchBlob.fetch('POST', 'https://helloapp.herokuapp.com/api/v1/upload', {
            'authorization': jwtToken,
            'Content-Type': 'multipart/form-data',
        },
            [
                { name: 'image', filename: 'avatar-png.png', type: 'image/png', data: base64logo },
                { name: 'name', data: name }
            ]
        ).then((resp) => {
            console.log(resp);
        }).catch((err) => {
            console.log(err);
        });
like image 432
kvadityaaz Avatar asked Nov 07 '22 13:11

kvadityaaz


1 Answers

I have solved the problem by using React-native-fetch-blob, but looking to solve using axios ,

here is the code :

 RNFetchBlob.fetch('POST', 'https://helloapp.herokuapp.com/api/v1/upload', {
            'authorization': jwtToken,
            'Content-Type': 'multipart/form-data',
        },
            [
                { name: 'image', filename: 'avatar-png.png', type: 'image/png', data: base64logo },
                { name: 'name', data: name }
            ]
        ).then((resp) => {
            console.log(resp);
        }).catch((err) => {
            console.log(err);
        });
like image 96
kvadityaaz Avatar answered Nov 10 '22 00:11

kvadityaaz