将本机图像选择器上传到服务器

时间:2020-11-05 11:57:24

标签: javascript react-native

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 =异步()=> { const options = { 标题:“选择头像”, // noData:false, storageOptions:{ // skipBackup:是, 路径:“图片”, }, //多个: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);
};

但是出现此错误 enter image description here

1 个答案:

答案 0 :(得分:0)

这里的实际问题:

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

您正试图通过传递无效参数来创建FormData的新实例。根据{{​​3}},这种创建FormData的方法在传递HtmlElement可以传递的document.getElementById时有效(例如)。

根据您的情况创建FormData的正确方法是:

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