简体   繁体   中英

How to upload file to server in react native expo

I am trying to upload file to the server from my react native app. I get the file from using ImagePicker but unable to upload it on server. I every time server gives me 400. Any help would be great.

Here is my code

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);
    });
};

You need to use contetType:multipart/form-data
this might help you,

React Native - Axios - Trying to upload image

How do I set multipart in axios with react?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM