'How to send an image from React-Native app to the Django server using Expo ImagePicker?

const [image, setImage] = useState(null);

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result.uri);

    if (!result.cancelled) {
      setImage(result);
    }
    
  };

I study React-Native and Django and I know about FormData, but I don't understand how put into my code.



Solution 1:[1]

Try the below code

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: true,
          aspect: [4, 3],
          quality: 1,
        });
    
        console.log(result.uri);
    
        if (!result.cancelled) {
          postToServer(result)// must be a object not array, if its array find first element if selecting only one image
          setImage(result);
        }
        
      };
    
    
//just function to upload to server

    const postToServer = (img)=>{
    const formData = new FormData();
    
    formData.append('photo', {
                uri: img.uri,
                type: 'image/jpeg', // or photo.type
                name: 'testPhotoName'
            });
     
    
        const options = {
          method: 'POST',
          body: formData,
          // If you add this, upload won't work
          // headers: {
          //   'Content-Type': 'multipart/form-data',
          // }
        };
        
        fetch('your-upload-url', options);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aman Deep