Cap'n Jack February 2016

Retrieve image data from file input without a server

For context, I'm trying to create a "click image" file uploader. Initially there is a default image, which I then click. I trigger a file upload, and the user picks an image file they want. Then I will set the image to replace the default (and do other things with it later). Right now, the front end looks something like this:

<div class="right-preview">
    <input type="image" src="img/logo.png" height="240px" width="240px" ng-click="uploadImage('right-image')" id="upload-right-image"/>
    <input type="file" id="upload-right" style="visibility: hidden">
</div>

When the image is clicked, it triggers an upload action.

$scope.uploadImage = function(side) {
    $image = $('#upload-' + side);
    $fileInput = $('#upload-right');

    $fileInput.change(function(changeEvent) {
    var files = changeEvent.target.files;

    for(var i = 0; i < files.length; i++) {
        file = files[i];
            console.log(file);
        }
    });

    $fileInput.trigger('click');
}

When the change event is fired after the user finishes picking their file, I have the changeEvent and I know they've selected their file. Each of the files has some properties (like name and size) but I'm not seeing anything for accessing the raw data so I can set the src on my other element.

Am I just completely missing how to get the image data, or is there a better way to do this? I have no server (right now) to post this to. Perhaps there is a better way to approach this?

Answers


ThisClark February 2016

This link may be helpful to you - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

I took one method from that page and added some additional functionality to hide the file upload button and have the image placeholder trigger its click event.

$('#placeholder').click(function() {
  $('#img-upload').trigger('click');
});

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<img width="250" height="250" id="placeholder" src="http://placehold.it/250x250&text='click to upload'">
<input class="hidden" type="file" onchange="previewFile()" id="img-upload">

Post Status

Asked in February 2016
Viewed 1,172 times
Voted 7
Answered 1 times

Search




Leave an answer