Skip to content

Instantly share code, notes, and snippets.

@taragano
Last active August 1, 2019 06:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taragano/a000965b1514befbaa03a24e32efdfe5 to your computer and use it in GitHub Desktop.
Save taragano/a000965b1514befbaa03a24e32efdfe5 to your computer and use it in GitHub Desktop.
Client side signed uploads with pure Javascript and PHP
<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