javascript - Retrieve image data from file input without a server -


for context, i'm trying create "click image" file uploader. there default image, click. trigger file upload, , user picks image file want. set image replace default (and other things later). right now, front end looks 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 image clicked, triggers upload action.

$scope.uploadimage = function(side) {     $image = $('#upload-' + side);     $fileinput = $('#upload-right');      $fileinput.change(function(changeevent) {     var files = changeevent.target.files;      for(var = 0; < files.length; i++) {         file = files[i];             console.log(file);         }     });      $fileinput.trigger('click'); } 

when change event fired after user finishes picking file, have changeevent , know they've selected file. each of files has properties (like name , size) i'm not seeing accessing raw data can set src on other element.

am missing how image data, or there better way this? have no server (right now) post to. perhaps there better way approach this?

this link may helpful - https://developer.mozilla.org/en-us/docs/web/api/filereader/readasdataurl

i took 1 method page , added additional functionality hide file upload button , have image placeholder trigger 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 upload'">  <input class="hidden" type="file" onchange="previewfile()" id="img-upload">


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -