Client side signed uploads with pure Javascript and PHP
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
<html> | |
<body> | |
<h1>Upload to Cloudinary with FormData</h1> | |
<form action="" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> | |
<fieldset> | |
<legend>Upload example</legend> | |
<p> | |
<label >Select your photo: | |
<input type="file" name="file"></label> | |
</p> | |
<p> | |
<input type="submit" value="Submit" /> | |
</p> | |
<img id="uploaded"> | |
<div id="results"></div> | |
</fieldset> | |
</form> | |
<?php | |
$cloud_name = "cloud_name"; | |
$api_key = "api_key"; | |
$api_secret = "api_secret"; | |
$timestamp = time(); | |
$signature = sha1("timestamp=".$timestamp.$api_secret); | |
?> | |
<script> | |
window.ajaxSuccess = function () { | |
response = JSON.parse(this.responseText); | |
console.log("ajaxSuccess", typeof this.responseText); | |
document.getElementById('uploaded').setAttribute("src", response["secure_url"]); | |
document.getElementById('results').innerText = this.responseText; | |
} | |
window.AJAXSubmit = function (formElement) { | |
console.log("starting AJAXSubmit"); | |
var xhr = new XMLHttpRequest(); | |
xhr.onload = ajaxSuccess; | |
var formData = new FormData(formElement); | |
formData.append("timestamp", <?php echo $timestamp ?>); | |
formData.append("signature", "<?php echo $signature ?>"); | |
formData.append("api_key", <?php echo $api_key ?>); | |
console.log(formData); | |
xhr.open("post", "https://api.cloudinary.com/v1_1/<?php echo $cloud_name ?>/image/upload"); | |
xhr.send(formData); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment