如何在React Native Expo中将文件上传到服务器

时间:2020-11-03 10:33:48

标签: android react-native

我正在尝试从我的本机应用程序将文件上传到服务器。我使用ImagePicker获取了文件,但是无法将其上传到服务器上。服务器每次给我400。 任何帮助都会很棒。

这是我的代码

MyProfile.tsx

const handleProfileUpdate = async () => {
    if (Platform.OS !== "web") {
      const { status } = await ImagePicker.requestCameraRollPermissionsAsync();
      if (status !== "granted") {
        alert("Sorry, we need camera Permissions");
      } else {
        const result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: true,
          aspect: [4, 3],
          quality: 1,
          //base64: true,
        });

        const localUri = result.uri;
        console.log("ImagePIcker", localUri);
        if (!result.cancelled) {
          setProfileImage(localUri);
          updateProfile(localUri);
        }
      }
    }
  };

userActions.ts

export const updateUserProfilePicture = (url: string) => async (
  dispatch: any
) => {

  var data = new FormData();  
  data.append("profilepic", url);
  console.log("profileUrl", url);
  const _rest = new restServices();
  const token = await _rest.getAccessToken();
  
  var config: AxiosRequestConfig = {
    method: "put",
    url: "http://xxxxxxxxxx/user/profilePic",
    headers: {
      Authorization: "Bearer " + token,
    },
    data: data,
  };
  axios(config)
    
    .then((res) => {
      console.log("profileUpdate", res);
    })
    .catch((err) => {
      console.log("profileupdate", err);
    });
};

1 个答案:

答案 0 :(得分:0)

您需要使用contetType:multipart / form-data
这可能对您有帮助,

React Native - Axios - Trying to upload image

How do I set multipart in axios with react?