【问题标题】:FormData sends string value instead of video file in react-nativeFormData 在 react-native 中发送字符串值而不是视频文件
【发布时间】:2020-05-18 23:28:43
【问题描述】:

我正在尝试使用 FormData 将我的视频上传到后端服务器。但是在上传视频文件时,我得到的是字符串值而不是后端的视频文件。谢谢

const formData = new FormData();
formData.append('dare_id', `${encrypted_id}`);
formData.append(
  'video',
  Platform.OS === 'android'
    ? uri                                 //local video file uri
    : uri.replace('file://', ''),        //local video file uri
);

fetch(UPLOAD_URL, {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${token}`,
    Accept: 'application/json',
  },
  body: formData,
})
  .then(res => res.json())
  .then(responseJson => {
    console.log(responseJson);
  })
  .catch(error => {
    console.log(error, ' error uploading');
  });

【问题讨论】:

    标签: react-native fetch


    【解决方案1】:

    对于上传文件,您还必须插入文件类型和文件名。这是他的代码:

    let formData=new FormData();
    formData.append({uri:yourNormalizedUri,type:”I dont know exactly but it should be video/mp4 google it”, name:”video.mp4”});
    

    【讨论】:

      【解决方案2】:

      不带Content-Type 标头再试一次。这里有一篇文章:https://muffinman.io/uploading-files-using-fetch-multipart-form-data/

      我之前使用 Axios 以相同方式发送文件时遇到过这个问题。该库足够聪明,可以正确设置标题,除非您添加它们。我怀疑您看到的错误与必须准确的边界设置有关。

      因此,与其显式设置标题,不如尝试依赖默认值,并允许 fetch(或 axios)根据包含的表单字段之一的文件类型正确设置标题。

      【讨论】:

      • 它也不起作用。我认为在 react native 中,如果要上传文件,必须设置Content-Type,抱歉没有提及平台
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多