Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropzoneJS dataURL is undefined

I am making an upload script but I am stuck on getting the dataURL from "file" on the "addedfile" event, here is my code:

$(function() {

    var dropzone = new Dropzone('#avatar', {
        url: '/uploads/avatar',
        clickable: '.upload',
        maxFilesize: 5,
        maxFiles: 1,
        previewsContainer: false,
        headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    dropzone.on('addedfile', function(file) {
        window.test = file;
        document.getElementById('avatar').setAttribute('src', file.dataURL);
        $('#loader').show();
    });

    dropzone.on('success', function(file, result) {
        $('#avatar_url').val(result.url);
        $('#loader').hide();
    });
});

When the following line of the script gets executed:

document.getElementById('avatar').setAttribute('src', file.dataURL);

the src attribute of the image becomes undefined, if I console log file.dataURL it's also undefined but console logging just "file" logs the object correctly; however when I go to the browser console and do this:

console.log(test.dataURL);

it correctly outputs the data url and I can successfully use it.

Here is a screenshot of the "file" logged to the console:

enter image description here

like image 887
Petar Vasilev Avatar asked May 15 '18 13:05

Petar Vasilev


1 Answers

The thumbnail is generated asynchronously, meaning the dataURL has not yet been generated when the addedfile event is emitted. There is a thumbnail event which is emitted when the thumbnail has been generated, passing the dataURL value as the second parameter.

You could do:

dropzone.on('thumbnail', function(file, dataURL) {
    document.getElementById('avatar').setAttribute('src', dataURL);
});
like image 189
Fredrik Jungstedt Avatar answered Oct 21 '22 19:10

Fredrik Jungstedt