Last active
April 6, 2017 17:53
-
-
Save jpoutrin/351de50179dfc1dc02cdf2d1a82417b8 to your computer and use it in GitHub Desktop.
Photo Uploader for Cloudinary compatible with react native - no jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CryptoJS from 'crypto-js'; | |
import _ from 'lodash'; | |
// http://cloudinary.com/documentation/upload_images#creating_api_authentication_signatures | |
const SUCCESS = 200; | |
export class Cloudinary { | |
constructor(apiSecret, apiKey, cloudName = 'my cloud name', createTimestamp = _.now) { | |
this.apiSecret = apiSecret; | |
this.apiKey = apiKey; | |
this.cloudName = cloudName; | |
this.createTimestamp = createTimestamp; | |
} | |
signQuery(payload){ | |
let first = true; | |
let toSign = ''; | |
_.each(payload, (value, key) => { | |
toSign += `${first?'':'&'}${key}=${value}`; | |
first = false; | |
}); | |
console.log('signature', toSign); | |
return CryptoJS.SHA1(toSign + this.apiSecret).toString(); | |
} | |
uploadImage(uri) { | |
let upload_url = 'https://api.cloudinary.com/v1_1/' + this.cloudName + '/image/upload'; | |
let xhr = new XMLHttpRequest(); | |
xhr.open('POST', upload_url); | |
xhr.onload = () => { | |
if (xhr.status === SUCCESS && onUploadComplete) { | |
console.log('photo uploaded successfuly'; | |
} | |
else { | |
console.log('something went wrong', xhr); | |
} | |
}; | |
const formdata = new FormData(); | |
// needs to be ordered as the Signed Query do not ensure the order for now. | |
const formPayload = { | |
folder: 'my_folder', | |
timestamp: this.createTimestamp() | |
}; | |
const signature = this.signQuery(formPayload); | |
formdata.append('file', {uri: uri, type: 'image/png', name: 'upload.png'}); | |
formdata.append('api_key', this.apiKey); | |
_.each(formPayload, (value, key) => { | |
formdata.append(key, value); | |
}); | |
formdata.append('signature', signature); | |
xhr.send(formdata); | |
return xhr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment