Search code examples
react-nativeexpressexpomulter

How to upload image to node js server from react native (expo) using fetch


I am not receiving data on the server side. Sometimes I get data as an object. I have tried different ways but the image upload gets failed. Below is my code. I have tried different method but the result was the same image folder remain empty as am using multer middleware

Image is getting displayed using this snippet

<TouchableHighlight
  style={[
    styles.profileImgContainer,
    { borderColor: "#4632a1", borderWidth: 1 },
  ]}
  onPress={openImagePickerAsync}
>
  <Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} />
</TouchableHighlight>

This is the Image Picker Section

function PickImage() {
  let [selectedImage, setSelectedImage] = useState("");
  let openImagePickerAsync = async () => {
    let permissionResult =
      await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      alert("Permission to access camera roll is required!");
      return;
    }

    let pickerResult = await ImagePicker.launchImageLibraryAsync();
    if (pickerResult.cancelled === true) {
      return;
    }

    setSelectedImage({ localUri: pickerResult.uri });
  };
}

Fetch API Call

async function upload() {
  const data = new FormData();
  data.append("image", {
    uri: selectedImage.uri,
    name: selectedImage.title,
    type: selectedImage.type,
  });

  const setting = {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data;",
    },
    body: data,
  };
  try {
    const fetchResponse = await fetch(url, setting);
    const data = await fetchResponse.json();
    alert(data);
  } catch (e) {
    alert(e);
  }
}

Server-Side Code

app.post("/users", upload.single("image"), async (req, res) => {
  console.log(req.body.file);
  console.log(req.body);
  const img = req.body.image;
  if (!img) {
    console.log("no image");
  }

  res.send({ congrats: "data recieved" });
});

Solution

  • I have tried different methods to send my file through fetch and axios API but multer wasnt able to find my image uri as it accept file so instead of going into that stuff you can simply stringfy your uri of image and send it to your nodejs server

    axios Api

    const formData=new FormData()
      var imageJSON = {
        imageName:new Date().getTime()+"_profile",
        avatar:selectedImage,
        name:name,
        email:email,
        SocietyCode:sCOde,
        password:Password
      }
    
      formData.append('image', JSON.stringify(imageJSON))
    
      axios.post('http://localhost:3000/users',formData,{
        headers:{
          Accept: 'application/json',
          'Content-Type':'multipart/form-data'
        }
      }).then((responseData) => {
        console.log("before",responseData.data)
          
        })
        .catch((error) => {
          alert(error)
          console.log("ERROR " + error.message)
        });
    

    Node ServerSide Code

    router.post('/users', upload.single('avatar'), async (req,res)=>{
          
            formData =await req.body;
            var userJSON =await JSON.parse(formData.image);
        
      const avatar =await Buffer.from(userJSON.avatar, "utf-8");
    
      delete userJSON.avatar
    userJSON.avatar=avatar
    console.log(userJSON)
    
    
     const user= new Users(userJSON)
            try{
    
              
                await user.save()
                res.send({'message':'Registeration Successfull'})
    
            }
            catch(e){
                res.send({'response':'registeration failed'})
                console.log(e)
            }
              
          })