Upload to Cloudinary with pure JavaScript
by Shirly Manor
HTML
<h1>Upload to Cloudinary with FormData</h1>
<div>
<p>
Set your cloud name in the API URL in the code: "https://api.cloudinary.com/v1_1/<strong><cloud name></strong>/image/upload" before running the example.
</p>
</div>
<form action="" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
<fieldset>
<legend>Upload example</legend>
<p>
<label for="upload_preset">Unsigned upload Preset: <input type="text" name="upload_preset">(set it <a href="https://cloudinary.com/console/settings/upload#upload_presets">here</a>)</label>
</p>
<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>
JavaScript
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");
if (!formElement.action) { return; }
var xhr = new XMLHttpRequest();
xhr.onload = ajaxSuccess;
xhr.open("post", "https://api.cloudinary.com/v1_1/shirly/video/upload");
xhr.send(new FormData(formElement));
}