使用 axios 反应原生上传图像

问题描述 投票:0回答:3

我有这个数据 来自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

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

有人从React Native 0.61.5版本开始讨论这个问题 在此链接中问题

reactjs typescript axios react-native
3个回答
1
投票

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

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;
  });

0
投票

这就是 axios post 请求与文件在 React-Native 中工作的原因(不确定 React)。

解决方案属于@MohamdAlmhde

const data = new FormData();

data.append('file', {
        uri,
        name: 'test',
        type: 'image/jpg',
      });

await axios({
        method: 'post',
        url,
        data,
        headers: {'Content-Type': 'multipart/form-data'},
      });

axios.post(url, data, config)
官方 axios 网站上给出的示例不起作用。


-2
投票

而不是使用,axiom使用简单的fetch,上传图像的方法

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
}
© www.soinside.com 2019 - 2024. All rights reserved.