简体   繁体   中英

jQuery image preview on change

I'm using the function below to display an image preview after selecting the file.
If the file extension eq the fileTypes it should display the image preview, but it doesn't.
Wat i'm doing wrong ?

var previewImage = function(input, block){
    var fileTypes = ['jpg', 'jpeg', 'png'];
    var extension = input.files[0].name.split('.').pop().toLowerCase();  /*se preia extensia*/
    var isSuccess = fileTypes.indexOf(extension) > -1; /*se verifica extensia*/

    if(isSuccess){
        var reader = new FileReader();
        reader.onload = function (e) {
            block.attr('src', e.target.result);
        };
    }else{
        alert('Fisierul selectat nu este acceptat!');
    }

};

$s(document).on('change', '#image', function(){
    previewImage(this, $s('.imagePreview'));
});

And here is my input.

      <div class="control-group form-group">
        <label for="image">Imaginea</label>
        <div id="imagePreview">
          <img src="/admin/mmadmin/template/assets/img-upload-150_150.png" class="imagePreview thumbnail" style="max-width:150px; max-height:150px;" />
        </div>
        <input type="file" name="imageFile" id="image" />
      </div>

Working fiddle: http://jsfiddle.net/8ns1s0zn/1/

Ok so there's a couple of issues: first of all, that s after jQuery's $.

$(document).on('change', '#image', function(){
    previewImage(this, $('.imagePreview'));
});

Then, you forgot to tell the reader to read the data:

reader.readAsDataURL(input.files[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM