0

I am trying to upload an image from my react native app to the nodejs and to the cloudinary cloud, but its not working for me. Thats my react-native code:

const App = () => {
  const [profileImageSource ,setProfileImageSource] = useState(require('./images/profilePic.png'));
  const [imageData, setImageData] = useState("");
  const [okay, setOkay] = useState(false);

  const config = {
    withCredentials: true,
    baseURL: 'http://localhost:3000/',
    headers: {
      "Content-Type": "application/json",
    },
  };
  const handleProfileImage = () => {
      const options = {
        title: 'Select photo',
        base64: true
      };

      ImagePicker.showImagePicker(options, (res) => {
        if(res.didCancel){
        }
        else if(res.error){
        }
        else{
          const image = {data: res.data};

          axios
          .post('/clients/upload-image', {
            data: JSON.stringify({image})
          },
          config
        )
          .then((res) => console.log("ok"))
          .catch((err) => alert(err));
        }
      })
    }

And that's my nodesjs code:

require('dotenv').config();

const cloudinary = require('cloudinary').v2;

//Cloudinary configurations
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

app.post('/clients/upload-image', (req, res) => {
    const imageStr = req.body.data;
    const uploadedResponse = 
        cloudinary
        .uploader
        .upload(imageStr, {
            upload_preset: 'user',
        })
        .then((uploadedResponse) => console.log(uploadedResponse))
        .catch((err) => console.log("error"));
}

Where am I wrong? I keep getting errors and the pictures are not uploaded to the cloudinary

Omer Ohana
  • 3
  • 1
  • 3

2 Answers2

0

Can you share the error message you've received? Also, can you confirm that imageStr (aka req.body.data) is received correctly in the backend? (maybe print it before uploading?)

ekt
  • 101
  • 3
0

Here is a simple for File uploading and using formidable as your bodyParser it will make your life easy using formidable, same might vouch for multer now that comes down to preference

So firstly I would advise that in your client you also use JavaScript FormData(built-in lib)

  • So how you would handle things when time to send picture to server is like this below:
const uploadPicture = ()=>{

    const data = new FormData();
    
    data.append('image', file)// So 'image' is the key and **file** now this is the file uploaded in user that you have in state
    
    axios.post(url, data).then(res=>{
        
         console.log(res)
    
    }).catch(err=>{

        console.log(err)

    })

}

Now how handle things is back-end

  • Firstly install npm i formidable or yarn add formidable
  • Once that is done you ready to go.
const cloudinary = require('cloudinary').v2;
const Formidable = require('formidable');

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

router.post('/api/upload', (req, res)=>{

    const form = new Formidable.IncomingForm();//Here you initialze your formidable instance
    form.parse(req, (error, fields, files)=>{
      
       const {image} = files //So due to in our request we sent a **file** which is an image then formidable parsed that request and placed file received from client in **files** that you see in callback function so now we de-structure it by key that we set in client

        cloudinary.uploader.upload(image.path, {folder:'here you can specify folder you want'}, (err, results)=>{

            if (err) return console.log(err)
            const image_url = results.secure_url
        }) 

    })

})
  • Now like this you uploaded your image

If this did not make sense to you: Here is a shameless plug