React-native-fetch-blob: Upload file using "POST"

Created on 12 Jul 2017  路  9Comments  路  Source: wkh237/react-native-fetch-blob

It's smilier to #413 . I closed that issue because I got the problem in upload method now....
Latest version (0.10.6)

Currently my parameter:

var params = {
    f_oc: "avatar-u",
    f_aaid: f_aaid,
    f_image: RNFetchBlob.wrap(s_filepath)
};

and my upload code is:

const url = "http://192.168.123.251:6671/content-u";

RNFetchBlob
.config({
    trusty : true
})
.fetch(
    'POST', 
    url, {
        'Content-Type' : 'multipart/form-data',
    }, params)
.then((res) => {
    console.log(res);
    callback(res);
})
.catch((errorMessage, statusCode) => {
    console.log("Error: "+ errorMessage + " - " + statusCode);
})

The code seems like no problem but I got red screen error "JSON value (... params) of type NSDictionary cannot be converted to NSString"

I tried to follow the example to convert params to an array (Add [] ) but the app will force close.

Most helpful comment

I found the problem. This is the correct format of params.
Thanks

        var params = [{
            name: "f_oc",
            data: "avatar-u"
        }, {
            name: "f_aaid",
            data: f_aaid
        }, {
            name: "f_image",
            filename : 'avatar.png', // elements without property `filename` will be sent as plain text
            data: RNFetchBlob.wrap(s_filepath)
        }];

All 9 comments

I found the problem. This is the correct format of params.
Thanks

        var params = [{
            name: "f_oc",
            data: "avatar-u"
        }, {
            name: "f_aaid",
            data: f_aaid
        }, {
            name: "f_image",
            filename : 'avatar.png', // elements without property `filename` will be sent as plain text
            data: RNFetchBlob.wrap(s_filepath)
        }];

what is the name in the params? How to upload a file with params(other data)?

@gitlovenotwar The name of the params is depends on your server. In my situation, the name is f_image.
filename parameter is use for make data not sent as plain text.
Finally the data is the path of the file and use "RNFetchBlob.wrap" function to make it sent as a file

okay, so name is the key for the server for the file name?, so in order to send more data, it will be like this?

body = [ {
   name: "f_image",
   filename : 'avatar.png', // elements without property `filename` will be sent as plain text
   data: RNFetchBlob.wrap(s_filepath)
}, 
// ... my other data to be sent
{
   name: "id"
   data: "1"
}, {
   name: "last_name"
   data: "Doe"
},
....]

Nope.. Name is the key of your data.
What's the meaning of "send more data?"

does the example on my code, correct?

Yes, that's correct

I see, thank you :)

@wayne1203 you're a God! thanks man, been struggling with this solution for almost a week! i was getting frustrated. Kudos for you mate.

Was this page helpful?
0 / 5 - 0 ratings