Franco Coronel
Franco Coronel

Reputation: 730

Upload base64 image in react native API request

I tried to upload a base64 image cropped to 600,400 and when i do the request its tell me unexpected token '>' but when i do an upload from an image cropped 20,20 the api call works. So its a problem of length of the base64 it seems that i cannot be to large I also tried to encoded but is large too the 600,400. So i have to resign myself to send a small image or there is another way.

This is my code of the image:

ImagePicker.openPicker({
            width: 600,
            height: 400,
            cropping: true,
            includeBase64: true
        }).then(image => {
            uploadPictureVar = 'data:image/jpeg;base64,' + image.data;
            window.picture = uploadPictureVar;
            this.setState({ uploadPicture: uploadPictureVar });
        });

And this is my api call

export function uploadPost(post) {
    let data = {
        body: post.body,
        picture: post.picture,
        type: post.type,
        user: {
            _id: post.user._id,
            name: post.user.name,
            picture: post.user.picture
        }
    }

    var headers = {
        'Content-Type': 'application/json',
        'Access-Control-Origin': '*'
    }

    return fetch(URL + "/uploadPost", {
        method: "post",
        headers: headers,
        body: JSON.stringify(data)
    })
        .then(response => Promise.resolve(response.json()))
        .catch(err => {
            return Promise.reject(err);
        })
}

Thanks

Upvotes: 0

Views: 6870

Answers (2)

Franco Coronel
Franco Coronel

Reputation: 730

I could solved it using this plugin : https://github.com/bamlab/react-native-image-resizer

This is my code:

ImageResizer.createResizedImage(window.picture, 600, 400, "PNG", 100, 0, null).then((response) => {
                alert(response)
                bodySendNewPost.picture = response.uri;
                // response.uri is the URI of the new image that can now be displayed, uploaded...
                // response.path is the path of the new image
                // response.name is the name of the new image with the extension
                // response.size is the size of the new image
              }).catch((err) => {
                  alert(err)
                // Oops, something went wrong. Check that the filename is correct and
                // inspect err to get more details.
              });

Upvotes: 0

jaywhy13
jaywhy13

Reputation: 1116

Is it possible to use the Chrome inspector to see the response you're getting back from the server. Maybe the backend is throwing an error and rendering a HTML page, hence the error... Unexpected '<'. I'm guessing you're trying parse JSON but you got a HTML response instead.

Upvotes: 3

Related Questions