简体   繁体   中英

react-native-image-picker doen`t upload to server

export const updateUserAvatarResponse = async data => {

const resp = await fetch(config.domain + '/api/users/update/avatar/', {
    method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + data.access,
    },
    body: new FormData('avatar', {
        type: 'image/jpeg',
        uri: data.avatar.uri,
        name: 'filename.jpg',
        // data: data.avatar,
    }),
});

return await resp.json();

};

updateAva = async () => { const options = { title: 'Select Avatar', // noData: false, storageOptions: { // skipBackup: true, path: 'images', }, // multiple: true, // includeExif: true,

    };

    ImagePicker.showImagePicker(options, (response) => {
        if (response.uri) {
            this.setState({
                imageData: response.uri,
                data: response
            });
            this.uploadImage();
        }
    });
};

uploadImage = async () => {
    const access = await getAccessToken();

    const resp = await updateUserAvatarResponse({
        access: access,
        avatar: this.state.data
    });

    console.log(this.state.data);

    console.log(resp);
};

But get this error enter image description here

The actual problem here:

body: new FormData('avatar', {
    type: 'image/jpeg',
    uri: data.avatar.uri,
    name: 'filename.jpg',
    // data: data.avatar,
}),

You are trying to create new instance of FormData by passing there non-valid arguments. According to the documentation of FormData , this approach of creating FormData is valid when you pass a HtmlElement that you can get from document.getElementById (as example).

The right way of creating FormData in your case would be:

let data = new FormData();
data.append('avatar', {
   type: 'image/jpeg',
   uri: data.avatar.uri,
   name: 'filename.jpg',
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM