Using $(this) with FileReader() to target result

前端 未结 2 902
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 15:44

I\'m trying to show an ajax preview of an image from a file input. Easy enough using FileReader() but I\'m using it with a loop so I when it\'s time to place the result inside a

相关标签:
2条回答
  • 2021-02-06 16:05

    This is how I would do it. Assign the target to the reader object itself and use it later.

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            // set where you want to attach the preview
            reader.target_elem = $(input).parent().find('preview');
            reader.onload = function (e) {
               // Attach the preview
               $(reader.target_elem).attr('src', e.target.result);
            };
    
            reader.readAsDataURL(input.files[0]);
        }
     }
    
    0 讨论(0)
  • 2021-02-06 16:10

    I had never worked with this API before. Interesting stuff.

    This version loops through all the file inputs and loads their preview images. The function is triggered by a button click.

    $(function(){
        $("#btnLoadPreviews").click(loadPreviews_click);
    })
    
    function loadPreviews_click(e) {
        $(".image").each(function() {
            var $input = $(this);
            var inputFiles = this.files;
            if(inputFiles == undefined || inputFiles.length == 0) return;
            var inputFile = inputFiles[0];
    
            var reader = new FileReader();
            reader.onload = function(event) {
                $input.next().attr("src", event.target.result);
            };
            reader.onerror = function(event) {
                alert("I AM ERROR: " + event.target.error.code);
            };
            reader.readAsDataURL(inputFile);
        });
    }
    

    If you prefer to have the preview image load as they are selected you could use this version instead.

    $(function(){
        $(".image").change(showPreviewImage_click);
    })
    
    function showPreviewImage_click(e) {
        var $input = $(this);
        var inputFiles = this.files;
        if(inputFiles == undefined || inputFiles.length == 0) return;
        var inputFile = inputFiles[0];
    
        var reader = new FileReader();
        reader.onload = function(event) {
            $input.next().attr("src", event.target.result);
        };
        reader.onerror = function(event) {
            alert("I AM ERROR: " + event.target.error.code);
        };
        reader.readAsDataURL(inputFile);
    }
    
    0 讨论(0)
提交回复
热议问题