qadenza
qadenza

Reputation: 9293

upload image and change source of an existing image

I need to upload an image and set the source of an existing image to that uploaded one
image is uploaded, but the new source doesn't work

<img class='avat' id='avat' src='ph/avat.jpg' alt='img'>
<input type='file' id='inpfile' accept=".jpg">

js

var imgavat = $('#avat');
var inpfile = $('#inpfile');
inpfile.on('change', function(){
    var uid = $('.aact').attr('data-id');
    var file = $(this).prop('files')[0];
    var form = new FormData();
    form.append('inpfile', file);
    form.append('uid', uid);
    $.ajax({
        url: "a_members_pro_plus.php",
        type: 'post',
        cache: false,
        contentType: false,
        processData: false,
        data: form,
        success: function(data){
            console.log(data); // avat/1.jpg - new source - ok
            imgavat.attr('src', data);  // doesn't work
            inpfile.val('');
        }
    });
});

Upvotes: 0

Views: 1008

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

You can combine FileReader with .readAsDataURL() in order to get a file and replace it with avatar.

When you select a file on your local computer with inpfile a change event is triggered.

In this event you need to test if there is one file (user selected a file):

this.files[0]

If the file exist you can instantiate the FileReader (required for reading the file) and add to it an handler for load end:

var reader  = new FileReader();
    reader.onloadend = function () {

When the file is completely loaded you can change the attribute of your avatar:

imgavat.attr('src', reader.result);

In order to start this async process you need to read the file as a data url so you can update the avatar src image:

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

The snippet:

var imgavat = $('#avat');
var inpfile = $('#inpfile');
inpfile.on('change', function() {
    if (this.files[0]) {   
        var reader  = new FileReader();
        
        reader.readAsDataURL(this.files[0]);
        
        reader.onloadend = function () {
            imgavat.attr('src', reader.result);
        };
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img class='avat' id='avat' src='ph/avat.jpg' alt='img'>
<input type='file' id='inpfile' accept=".jpg">

Upvotes: 1

Related Questions