如何在React Native中将图像上传到服务器

时间:2019-10-18 09:32:43

标签: react-native axios react-native-image-picker

我正在尝试使用React Native axios上传图像。但是我得到了这个回应。我尝试了所有解决方案,但没有成功。我正在使用react-native-image-picker获取图像

{ result: null,
  message: 'Wrong access',
  error: true,
  type: 'command_not_found' }

这是我的代码

    ImagePicker.showImagePicker(options, (response) => {

        let formData = new FormData();
        formData.append('image', { uri: response.uri, name: response.fileName, type:response.type });
        let config = {
           headers: {
                   'Content-Type': 'multipart/form-data'
           }
        }
        axios({
           url: "URL",
           method: 'POST',
           data: formData,
           config
         })
         .then(result => console.log(result))
         .catch(error => console.log(error))

     }

1 个答案:

答案 0 :(得分:0)

尝试使用原始fetch API。

const createFormData = (photo) => {
  const data = new FormData();

  data.append("photo", {
    name: photo.fileName,
    type: photo.type,
    uri:
      Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
  });

  return data;
};

然后尝试再次上传

fetch("http://localhost:3000/api/upload", {
    method: "POST",
    body: createFormData(photo)
});