与axios反应本机上传图像

时间:2020-07-27 04:41:55

标签: reactjs typescript react-native axios react-native-android

我有这个数据 来自react-native-image-picker

data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kb
fileName: "77677.jpg"
fileSize: 67542
height: 600
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/77677.jpg"
type: "image/jpeg"
uri: "content://media/external/images/media/18584"
width: 399
__proto__: Object

,然后尝试设置对象类型#FromData中的此数据以上传#img

var binaryDataInBase64 = new FormData();
        binaryDataInBase64.append('file', {
            // data: response.data,
            uri: 'file://' + response.uri,
            name: 'MMM.jpg',
            type: response.type
        })
        console.log('=======================>', binaryDataInBase64)
        axios.post(
            'https://danskeclouddemo.com/api/file',
            { file: binaryDataInBase64 },
            { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data'  } }
        ).then(res => {
            console.log(res)
        }).catch(error => {
            console.log(error)
        })

这是后端邮递员,工作得很好Postman collection

// ===================== // ====================== 编辑

有人在0.61.5之后从本机版本谈论问题 在此链接issues

2 个答案:

答案 0 :(得分:0)

相反,公理使用获取简单,上传方法,图像

this.setState({imageLoading:true})
    const credentials={
       userId:this.state.userId
    }
    try {
      let response = await fetch(
        'url',
        {
            'method': 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
             body: createFormData(source, credentials)
        }
      );
      
      if (response.status == 200) {
            response.json().then(data => {
            
            switch (data.status) {
                case 200:
                   
                    break;
            }
         });
      }else {
        this.setState({imageLoading:false ,isLoading:false})
             }
    } catch (error) {
      this.setState({imageLoading:false,isLoading:false})
      console.error(error);
    }


const createFormData=(image,body)=>{
var data = new FormData();
data.append(image, {
uri:  Platform.OS === "android" ? image.uri : image.uri.replace("file://", ""), 
name: `dummy${Date.now()}.jpg`,
type: 'image/*'
})


Object.keys(body).forEach(key => {
    data.append(key, body[key]);
});
return data
}

答案 1 :(得分:0)

您的表单数据必须是这样的。

formdata.append('file',{
    uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
    name: 'test',
    type: 'image/jpeg' // or your mime type what you want
});

然后

axios.post('/users/profilepic', formdata, config).then((res) => {
    console.log(res.data);
    return res.data;
  });