DropzoneJS dataURL is undefined
Asked Answered
M

1

7

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

Martelli answered 15/5, 2018 at 13:3 Comment(10)
What object do you get when you log the file? Make sure you're accessing the dataURL field properlyQuarry
The object is called "File" and it has dataURL as property @VincentNguyenMartelli
Can you post a screenshot of the file object logged to the consoleQuarry
I've added a screenshot @VincentNguyenMartelli
Is addedfile an asynchronous function?Quarry
You mean this kind of function: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… if yes then noMartelli
I am not familiar with dropzoneJS, but it seems that addedfile is asynchronous (I thought so because the screenshot shows a http request). So you may be trying to access the dataUrl before it is available. See if the solution here is of any help: #25927881Quarry
I haven't tried it but I think it will work @VincentNguyen thanksMartelli
@VincentNguyen you are right, also stated in the documentation dropzonejs.com/#event-thumbnailStefaniestefano
Awesome, should work for him thenQuarry
F
6

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);
});
Fixity answered 4/3, 2021 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.