Photo Uploader

by Toshi Takeuchi

HTML

<h2>Photo Uploader</h2>
<div id="msgbox" class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <span id="message"></span>
</div>
<input type="file" id="file" name="file" accept="image/*" />
<p>
  <output id="list"></output>
</p>

CSS

.alert {
  padding: 20px;
  background-color: #4CAF50;
  color: white;
  font-weight: bold;
  margin-bottom: 15px;
}

.closebtn {
  margin-left: 15px;
  color: white;
  font-weight: bold;
  float: right;
  font-size: 22px;
  line-height: 20px;
  cursor: pointer;
  transition: 0.3s;
}

.closebtn:hover {
  color: black;
}

.thumb {
  height: 150px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}

JavaScript

// This function runs when the page is loaded
$(document).ready(function() {
  // Check for the various File API support.
  if (window.File && window.FileReader && window.FileList && window.Blob) {
    $('#message').text('Please choose a photo.');
  } else {
    $('#message').text('The File APIs are not fully supported in this browser.')
    $("#msgbox").css("background-color", "#ff6666");
  }
  // attach event listener
  $('#file').change(handleFileSelect)
});

// run when the file button is clicked
function handleFileSelect(evt) {
  var f = evt.target.files; // FileList object

  // Only process image file
  if (!f[0].type.match('image/*')) {
    $('#message').text('Please choose a photo.');
    $("#msgbox").css("background-color", "#ff6666");
    return;
  };
  
  // display the thumbnail of the chosen image
  var thumb = $('<img class="thumb">');
  thumb.attr('src', window.URL.createObjectURL(f[0]));
  thumb.onload = function() {
    window.URL.revokeObjectURL(this.src);
  }
  thumb.attr('title', escape(f[0].name));
  $('#list').append(thumb);
  
  // upload the chosen image
  fileUpload(f[0]);
};

// upload the image and get image label
function fileUpload(file) {
  $('#message').text('Sending File...');
  $("#msgbox").css("background-color", "#4CAF50");

  var reader = new FileReader(); // FileReader object
  reader.onload = function(e) {
    var dataURL = reader.result;
    $.ajax({
      url: 'http://ec2-52-38-254-185.us-west-2.compute.amazonaws.com:31415/dlbot/identify',
      type: 'POST',
      timeout: 10000, // sets timeout to 10 sec
      data: JSON.stringify({
        "rhs": dataURL, // input arguments
        "nargout": 1 // number of return valeus
      }),
      contentType: 'application/json',
      success: function(data) {
        if (data.hasOwnProperty('lhs')) { // if lhs property exists
          var label = data.lhs[0].mwdata[0]; // return value is label
          $('#message').text(label);
          $('#msgbox').css("background-color",...