React Native upload image with axios and expo image picker

605 views Asked by At

i'm trying to upload a image with expo image picker and axios.

It's my code:


// Select image from Library <--comment
  const selectImage = async () => {
    // Get iamge
    try {
      // Check has library permission <--comment
      const hasLibraryPermission = await requestLibraryPermision();
      if (hasLibraryPermission) {
        // Lunch camers <--comment
        const result = await ImagePicker.launchCameraAsync();

        // Check is canceld or not <--comment
        if (!result.canceled) {
          // Set result uri to state <--comment
          const newInformation = { ...information };
          newInformation.data.image = result.assets[0].uri;
          setInformation(newInformation);

          // Define and append result to form data <--comment
          const formData = new FormData();
          formData.append("image", result.assets[0]);

          // Define request url <--comment
          const url = `${serverData.url}/profile/update-image`;

          // Send post upload image request <--comment
          await axios
            .post(url, formData, {
              headers: {
                "content-type": "multipart/form-data",
              },
            })
            .then((response) => {
              console.log("response: ", response.data);
            })
            .catch((error) => {
              console.log("CATCH ERROR: ", error);
            });
        }
      }
    } catch (error) {
      console.log("Error: ", error);
    }
  };

The request show this error log: CATCH ERROR: [AxiosError: Network Error] I searched in the web and even ask at the bard and chat gpt ai's but they can't answer me, whats the problem?

3

There are 3 answers

1
CharlieH On

I was having a problem with very similar symptoms and thought it was a client side issue, but in the end I realized I had misconfigured my Django server. As the other poster said, if the form data contains that data then the server should be able to parse it if configured correctly. If you happen to be using a Django server then it should look something like this:

class UploadImageView(APIView):
    parser_classes = (FormParser, MultiPartParser,)

  def post(self, request):
    try:
        image = request.data["image"]
        print("successfully uploaded it")
    except:
        print("Didnt do it")
0
Ngoc Huy On

Do you have AllowsEditing: true in your ImagePicker.launchImageLibraryAsync ?

I had the same error and i fixed it by:

1 - Seting AllowsEditing: false

2 - Instead of using axios or fetch to send request i used FileSystem.uploadAsync in expo-file-system

7
user18309290 On

A file object should have uri, name and type fields, something like this:

const formData = new FormData();
formData.append(
  'image',
  {
    uri: result.assets[0].uri,
    name: <name>,
    type: <type>
  }
);
axios.post(<url>, formData);