【问题标题】:Can't get a .post with 'Content-Type': 'multipart/form-data' to work Axios React Native无法使用 'Content-Type': 'multipart/form-data' 获得 .post 来工作 Axios React Native
【发布时间】:2020-01-15 00:48:59
【问题描述】:

我正在尝试上传 FormData,其中包括 文本、图像、pdf 等

我正在使用 axios

Axios 调用

const sellerRegister = params => {
  console.log(params);
  return dispatch => {
    dispatch(servicePending());
    return axios
      .post(`${BaseUrl}/seller/register`, params, {
        headers: {
          Accept: "application/json",
          "Content-type": `multipart/form-data; boundary=${params._boundary}`
        }
      })
      .then(res => {
        return dispatch(sellerRegisterSuccess(res));
      })
      .catch(err => {
        return dispatch(serviceError(err.message));
      });
  };
};

FormData 中的参数

服务错误

提供此错误的解决方案。并指导我这样做是否正确?

谢谢

【问题讨论】:

    标签: react-native post file-upload axios content-type


    【解决方案1】:

    使用最新版本的 Axios,您发出 HTTP 请求,标头中包含 'Content-Type': 'multipart/form-data',如下所示:

    const formData = new FormData();
    formData.append('action', 'ADD');
    formData.append('param', 0);
    formData.append('secondParam', 0);
    formData.append('file', new Blob(['test payload'], { type: 'text/csv' }));
    axios({
      url: 'http://your_host/api/auth_user',
      method: 'POST',
      data: formData,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data'
      }
    })
    

    使用 url 代替 uri。

    或 你可以这样做:

    axios.defaults.headers.common['Content-Type'] = 'multipart/form-data; 
    boundary=someArbitraryUniqueString';
    

    【讨论】:

    • 在新的 Blob(['test payload']) 中。 “测试有效载荷”是什么意思。 ?
    • 文件名,文件的uri?
    • 感谢您的帮助。实际上我遇到了另一个问题。我的调试器在那个应用程序没有正确处理请求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多