skip to Main Content

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?

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search