Ajax - Image upload producing multiple image preview from 2 input button

时间:2018-04-18 17:59:29

标签: php ajax html5

SOLVED

I edited ajax script like this and it's working now.

function **preview2**(input) {
        if (input.files && input.files[0]) {
            var freader = new FileReader();
            freader.onload = function (e) {
                $("#preview2").show();
                $('#preview2').attr('src', e.target.result);
            }
            freader.readAsDataURL(input.files[0]);
        }
    }

    $("#img2").change(function(){
        **preview2**(this);
    });

What I want like this picture :

HTML Code :

            <img id="preview1" src="avatar/<?php echo $rprofil['avatar'];?>" style="margin-bottom: 10px;" class="img-thumbnail img-profile">
        <form style="margin-bottom: 20px;">
            <label class="btn btn-primary btn-sm">
            Browse <i class="fas fa-image"></i> <input type="file" id="img1" style="display: none;">
            </label>
            <button type="button" class="btn btn-success btn-sm">Save <i class="fas fa-save"></i></button>
        </form>

            <img id="preview2" src="cover/<?php echo $rprofil['cover'];?>" style="margin-bottom: 10px;" class="img-cover img-thumbnail img-responsive">
        <form >
            <label class="btn btn-primary btn-sm">
            Browse <i class="fas fa-image"></i> <input type="file" id="img2" style="display: none;">
            </label>
            <button type="button" class="btn btn-success btn-sm">Save <i class="fas fa-save"></i></button>
        </form>

AJAX Code :

function preview(input) {
        if (img2 && input.files && input.files[0]) {
            var freader = new FileReader();
            freader.onload = function (e) {
                $("#preview2").show();
                $('#preview2').attr('src', e.target.result);
            }
            freader.readAsDataURL(input.files[0]);
        }
    }

    $("#img2").change(function(){
        preview(this);
    });

I added same 2 ajax script for img1(avatar) and img2(cover) preview. When I browse for avatar, it's preview appear on cover preview and when I browse for cover, it's preview correctly appear on cover preview. So how to make that avatar preview correctly ? Thanks a lot.

0 个答案:

没有答案