1

Hello I am new to react and I am trying to upload image from react native image picker but it is not uploading to node js server and Image data is not going to backend node js server

here is my react native code

import React,{useState,useEffect} from 'react'
import {View,Text,StyleSheet,SafeAreaView,TouchableOpacity,Image,Button,AsyncStorage} from 'react-native'
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-picker';

    const ActvityScreen = (props) =>
    {    
      const [u_id,setU_id] = useState('');
      const [image,setImage] = useState('https://bootdey.com/img/Content/avatar/avatar6.png');
      const [filePath,setfilePath] = useState({});

       useEffect(() => {
            async function fetchData() {
            const token = await AsyncStorage.getItem('token');
            fetch('http://127.0.0.1:3000',{
                headers:new Headers({
                    Authorization:'Bearer '+token
                })
            }).then(res=>res.json())
            .then(async(data)=>{
              // setIsloaded(false);
                console.log(data)

                setU_id(data.u_id)
                setImage('http://127.0.0.1:3000/image/'+data.photoId)
                console.log(image)
            })
            }
            fetchData();
          }, []); 



      const handleUploadPhoto = async (filePath) => {
      fetch("http://127.0.0.1:3000/updateImageprofile2", {
        method: "POST",
        body: createFormData(filePath, { userId: u_id }),
         headers: {
            Accept: 'application/json',
            'Content-Type': 'multipart/form-data',
          },
      })
        .then(response => response.json())
        .then(response => {
          console.log("upload succes", response);
          alert("Upload success!");
        })
        .catch(error => {
          console.log("upload error", error);
          alert("Upload failed!");
        });
    };


    const createFormData = (photo, body) => {
      const data = new FormData();
       console.log("photoooooooooooo",photo.fileName);

      data.append("photo", {
        name: photo.fileName,
        type: photo.type,
        uri:
          Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
      });

      Object.keys(body).forEach(key => {
        data.append(key, body[key]);
      });
      return data;
    };

      const chooseFile = () => {
        var options = {
          title: 'Select Image',
          customButtons: [
            { name: 'customOptionKey', title: 'Choose Photo from Custom Option' },
          ],
          storageOptions: {
            skipBackup: true,
            path: 'images',
          },
        };
        ImagePicker.showImagePicker(options, response => {
          console.log('Response = ', response);

          if (response.didCancel) {
            console.log('User cancelled image picker');
          } else if (response.error) {
            console.log('ImagePicker Error: ', response.error);
          } else if (response.customButton) {
            console.log('User tapped custom button: ', response.customButton);
            alert(response.customButton);
          } else {
            let source = response;
            setfilePath(source);
            handleUploadPhoto(source);
          }
        });
      };

        return (
            <View style={styles.container1}>

              <Image
                source={{
                  uri: 'data:image/jpeg;base64,' + filePath.data,
                }}
                style={{ width: 100, height: 100 }}
              />
              <Image
                source={{ uri: filePath.uri }}
                style={{ width: 250, height: 250 }}
              />
              <Text style={{ alignItems: 'center' }}>
                {filePath.uri}
              </Text>
              <Button title="Choose File" onPress={()=>chooseFile(this)} />
            </View>
            )
    }

    const styles = StyleSheet.create({
        container1:{
            flex:1,
            backgroundColor: '#fff',
        marginTop:16
        },
        text:{
            color:"#161924",
            fontSize:20,
            fontWeight: '500' 
        }
    })

    export default ActvityScreen;

Here when I click choosefile button function it goes to choosefile function and in console the image data is showing

and here is my backend code

const express = require('express');
const mongoose = require('mongoose');
const jwt  = require('jsonwebtoken');
const {jwtkey} = require('../keys');
const multer = require('multer');
const router = express.Router();
const GridFsStorage = require('multer-gridfs-storage');
const url = 'mongodb://localhost:27017/pixa';
const storage = new GridFsStorage({ url });
const uploadController = require("../controllers/upload");
const User = mongoose.model('User');

const upload = multer({ 
  dest: "upload/",
});

  router.post("/updateImageprofile2", upload.array('photo',3),async (req, res,next) => {
    console.log("I am in");
    console.log('files', req.files)
     console.log('file', req.file)
    console.log('body', req.body)
    res.status(200).json({
      message: 'success!',
    })
  });

module.exports = router
Satya
  • 59
  • 7

0 Answers0