【问题标题】:react-native upload image and data to api using axiosreact-native 使用 axios 上传图片和数据到 api
【发布时间】:2019-10-06 19:57:04
【问题描述】:

如何使用 axios 上传图片到 api

我想使用 axios 将带有数据的图像上传到 api 我尝试使用 formdata,但它不起作用,请参阅下面的代码

这是我的代码

uploadToServer= () => {
    const file =this.state.photo



let formdata = new FormData()
formdata.append('sale_id', 1)
formdata.append('note_type_id', 4)

formdata.append('description', "test")

formdata.append('note_content_item', "test")

formdata.append('Note', file)


   axios.post('api',
        {data:formdata},{headers: {
          'Content-Type' : 'multipart/form-data',
          'Authorization':'xx'
            }

          })
        .then(resp => console.log(resp))
        .catch(error => console.error(error)); 

}

我尝试了很多解决方案,但它给了我 错误:请求失败,状态码为 500

【问题讨论】:

  • axios 请求中“内容类型”的拼写错误。更改它并重试?
  • 谢谢@MickVader 现在我得到错误代码 500??
  • 您是否拥有服务器或有权访问它?如果是这样,您的请求 ping 时的服务器端堆栈跟踪可以帮助缩小范围。我想这与您的 formdata 对象有关,但如果邮递员成功了。Edit 尝试将 formdata 直接添加到 axios.post 请求的参数中:axios.post('api', formdata, {headers:...);
  • axios.post('api', formdata, {headers:...);现在我可以访问但我得到了这个响应 {“response”:{“message”:“无法保存文件”,“response_code”:10 } } 如果我将 KEY 数据更改为其他内容,我会在邮递员中收到此响应
  • 所以我将 key 从 formdata 更改为 data let data = new FormData() data.append('sale_id', '1') data.append('note_type_id', '4') data。 append('description', "test") data.append('note_content_item', "test") axios.post('api',data ,{headers: { but still got the same thing can't save file

标签: reactjs react-native axios


【解决方案1】:

500 Internal Server Error 是一个非常普遍的 HTTP 状态代码,表示服务器出现问题。 您可以这样请求(使用 fetch):

let formdata = new FormData()

formdata.append('description', "test")

let i = {
    uri: image.path,
    type: 'multipart/form-data',
    name: `image.jpg`,
};
formdata.append('image', i);

fetch(YourApi,{
    method: 'post',
    headers: {
        'Content-Type': 'multipart/form-data',
    },
        body: formdata
}).then(response => {
    response.text().then((res)=>{
        console.warn(res)
    })
}).catch(err => {
    console.warn('error')
})

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 2021-03-10
    • 2020-08-17
    • 2020-10-22
    • 2018-03-26
    • 2019-03-26
    • 2021-01-13
    • 2019-04-05
    • 2020-03-13
    相关资源
    最近更新 更多