0
votes

I am trying to upload image direct to cloudinary from react-native application. I am using Expo Imagepicker on react-native side and doing POST request using axios. I get a "400 Bad Request" from Cloudinary with error message -

Unsupported source URL: data%3Aimage%2Fjpg%3Bbase64%2CZmlsZTovLy9kYXRhL3VzZXIvMC9ob3N0LmV4cC5leHBvbmVudC9jYWNoZS9FeHBlcmllbmNlRGF0YS8lMjU0MGFub255bW91cyUyNTJGZXhwb3Rlc3QtZWY2NWJjYjktYTFiMC00N2JlLWE3ZDUtMmNmNThhOGM5ZWU1L0ltYWdlUGlja2VyL2NiN2FmMTUzLTA2OWItNDdlZS05NDdkLWU2ZDk1YTQ1MzI2Yi5qcGc%3D

Code in place is added below

let uri64 = base64.encode(uri);
let fileData = "data:image/jpg;base64," + uri64;
console.log('html escape: ' + encodeURIComponent(fileData));

let data = {
  upload_preset: CLOUDINARY_UPLOAD_PRESET,
  file: encodeURIComponent(fileData)
}
return axios.post(CLOUDINARY_UPLOAD_URL,data);
2
Can you please run your code without encoding fileData, see if it helps?Roee Ben-Ari

2 Answers

0
votes

Expo added an option to generate a base64 from imagepicker from SDK18. I have written an API to which the base64 is passed to, which inturn would call cloudinary methods.

0
votes

If you specify base64 in the ImagePicker, you can use the uri and base64 data returned to upload your image directly to Cloudinary. Here's an example using superagent:

const getImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
    base64: true
  })
  if (!result.cancelled) {
    const { uri, base64 } = result
    uploadImage(uri, base64)
  }
}

const uploadImage = (uri, base64) => {
  const uriArr = uri.split('.');
  const fileType = uriArr[uriArr.length - 1]
  const file = `data:${fileType};base64,${base64}`

  let upload = request.post(CLOUDINARY_UPLOAD_URL)
                      .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
                      .field('file', file)
                      .field('folder', CLOUDINARY_FOLDER);
  upload.end((err, response) => {
    if (err) {
      console.error(err)
    }
    if (response.body.secure_url !== '') {
      console.log(response.body.public_id)
    }
  })
}