I’ve implemented image uploading and processing enough times to desire using a service to handle it for me this time around. Enter Cloudinary, a service that appears to do just what I want: accept image uploads directly from client browsers bypassing my servers all together and serving the images up from a CDN.

They have open source javascript libraries for interfacing with their API, but their documentation is lacking unless you want to use their jQuery dependent implementation. I’m not using jQuery and want a plain JS solution. It should be as simple as using XMLHttpRequest to POST to their API right? Fortunately it is!

<input type="file" id="file" onchange="uploadFile()" />
function uploadFile() {
  var formData = new FormData(),
    file = document.getElementById("file").files[0],
    xhr = new XMLHttpRequest(),
    cloudName = "your Cloudinary cloud's name";

  formData.append("file", file);
  formData.append("upload_preset", "your unsigned upload preset"); // REQUIRED
  xhr.open("POST", "https://api.cloudinary.com/v1_1/" +
    cloudName +
    "/image/upload");

  xhr.onload = () => {
    if (xhr.status === 200) {
      // Success! You probably want to save the URL somewhere
      var response = JSON.parse(xhr.response);
      response.secure_url // https address of uploaded file
    } else {
      alert("Upload failed. Please try agian.");
    }
  }
  xhr.send(formData);
}

This solution is as simple as it gets. There’s no progress tracking, retrying, or pre-upload-optimizations and it works perfectly for what I need.

If you do want progress updates you’ll need to define an xhr.onprogress function. See Mozilla’s XMLHttpRequest.status documentation for more info.