React-native上载图片为FormData

时间:2018-10-24 04:16:52

标签: javascript react-native react-native-android react-native-image-picker

需要在React-Native中将图像作为formData发布

表单数据:

-WebKitFormBoundary4df7ukBk3N8GDzOl 内容处置:表单数据; name =“ selfieImage”; filename =“ 600px-Google_Drive_logo.png” 内容类型:image / png

-WebKitFormBoundary4df7ukBk3N8GDzOl-

我需要使用react-native-image-picker重新创建上面的代码,这是我的代码:

图像选择器代码:

ImagePicker.showImagePicker(options, (response) => {
        console.log('Response = ', response);

        if (response.didCancel) {
          console.log('User cancelled image picker');
        } else if (response.error) {
          console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
          console.log('User tapped custom button: ', response.customButton);
        } else {
            formData = new FormData();
            formData.append("selfieImage", {
                name: 'selfieImage', 
                filename: response.uri
            })
            console.log(formData)

        //   this.setState({
        //     photo: formData,
        //   });
        }
      });

Axios邮政编码:

 await axios({
        method: 'post',
        url: `${'{url}/home-security/image/selfie/' + this.state.newId}`,
        data: formData,
        config: { headers: {
            'Content-Type': 'multipart/form-data',
        }}
        })
        .then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });

1 个答案:

答案 0 :(得分:1)

我知道的方法是将图像转换为base64字符串并通过axios传递。但最好使用AWS S3之类的云服务来上传图像并发送图像URL。