Skip to content

Instantly share code, notes, and snippets.

@cmcewen
Created December 29, 2015 15:38
Show Gist options
  • Save cmcewen/b1ea2464aa88ae32be17 to your computer and use it in GitHub Desktop.
Save cmcewen/b1ea2464aa88ae32be17 to your computer and use it in GitHub Desktop.
Upload image from React Native to Cloudinary
var CryptoJS = require('crypto-js');
function uploadImage(uri) {
let timestamp = (Date.now() / 1000 | 0).toString();
let api_key = 'your api key'
let api_secret = 'your api secret'
let cloud = 'your cloud name'
let hash_string = 'timestamp=' + timestamp + api_secret
let signature = CryptoJS.SHA1(hash_string).toString();
let upload_url = 'https://api.cloudinary.com/v1_1/' + cloud + '/image/upload'
let xhr = new XMLHttpRequest();
xhr.open('POST', upload_url);
xhr.onload = () => {
console.log(xhr);
};
let formdata = new FormData();
formdata.append('file', {uri: uri, type: 'image/png', name: 'upload.png'});
formdata.append('timestamp', timestamp);
formdata.append('api_key', api_key);
formdata.append('signature', signature);
xhr.send(formdata);
}
@choows
Copy link

choows commented May 31, 2020

hi i had am new to cloudinary and caught some problem using the preview code. Please someone help me out .. Thanks. Code as below

uploadImage=(img_uri , _imgtype , fileName)=>{
CryptoJS = require('crypto-js');
let timespam = (Date.now() / 1000 | 0).toString();
let api_secret = '{Api Secret}';
let hash_string = 'timestamp=' + timespam + "&upload_preset=" + "{Upload Preset Name}" + api_secret;
let signature = CryptoJS.SHA1(hash_string).toString();

const uri = img_uri;
const type = _imgtype;
const name = fileName;
const source = {
  uri,
  type,
  name,
}

const data = new FormData()
data.append('api_key' , '{API Key}');
data.append("cloud_name", "{Cloud Name}");
data.append('file', source);
data.append('timestamp' , timespam);
data.append('resource_type' , 'image');
data.append('upload_preset', Upload Preset Name);
data.append('signature' , signature);
//below is using XMLHttpRequest to post

let xhr = new XMLHttpRequest();
xhr.open('POST', "https://api.cloudinary.com/v1_1/XXX/image/upload");
xhr.onload = () => {
  console.log("inside onload");
  console.log(xhr);
};

xhr.onreadystatechange=(e)=>
{
    if(xhr.status==200 && xhr.readyState==4)
    {
        //alert(xhr.responseText);
        console.log(xhr.response);
    }
    console.log("Here : " + JSON.stringify(xhr));
    console.log("Response Code : " + xhr.status  + "   " + xhr.statusText);
}
xhr.send(data);

}

turn out it return response "Stream Closed". and i using react-native-image-picker to get the uri, image type and iamge name. that part have no problem

@rvigneshw
Copy link

I got

{"error":{"message":"Unsupported Objec URL"}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment