ga-wdi-boston / rails-paperclip

Setting up Paperclip within a Rails app, both with local storage and with S3.
2 stars 10 forks source link

Show image instead of text confirmation. #10

Open GA-MEB opened 8 years ago

GA-MEB commented 8 years ago

Change front-end to show the image that's been uploaded instead of just giving a text confirmation.

GA-MEB commented 8 years ago
$(document).ready(function(){

  $('#submit').on('click', function(e){
    e.preventDefault();
    // creates a new instance of the FileReader object prototype
    var reader = new FileReader();

    //setting a function to be executed every time the reader successfully completes a read operation
    reader.onload = function(event){
      // once the data url has been loaded, make the ajax request with the result set as the value to key 'poster'
      $.ajax({
        url: 'http://localhost:3000/movies',
        method: 'POST',
        data: { movie: {
          title: $('#title').val(),
          release_year: $('#release').val(),
          poster: event.target.result
        } }
      }).done(function(response){
        // console.log("Uploaded successfully.")
        console.log(response);
        $("#show-movie").html('');
        $("#show-movie").append('<p>Created movie:' + response.title + '</p>');

        // Local file storage
        var idString = response.id.toString();
        idString = "000".substr(3 - idString.length) + idString;
        $("#show-movie").append('<img src="http://localhost:3000/system/movies/posters/000/000/' + idString + '/original/' + response.poster_file_name+ '">');

         // S3 storage

      }).fail(function(response){
        console.error('Whoops!');
      })
    };

    // read the first file of the file input
    $fileInput = $('#poster');
    reader.readAsDataURL($fileInput[0].files[0]);

  });
});