66

I Don't understand that... call its always undefined

Create the mock file:

var mockFile = { name: "Filename", size: 12345 };

Call the default addedfile event handler

myDropzone.options.addedfile.call(myDropzone, mockFile);

And optionally show the thumbnail of the file:

myDropzone.options. thumbnail.call(myDropzone, mockFile, "/image/url");
StKiller
  • 7,631
  • 10
  • 43
  • 56
Marcogomesr
  • 2,614
  • 3
  • 30
  • 41
  • The parameters of createThumbnailFromUrl has changed in Version > 5. To make it work again, check out this GitHub Issue: https://github.com/enyo/dropzone/issues/1587#issuecomment-324023260 – Paul Beck Jan 05 '18 at 15:16

9 Answers9

48

Finally !!

$(function() {
    var mockFile = { name: "banner2.jpg", size: 12345 };
    var myDropzone = new Dropzone("#my-awesome-dropzone");
    myDropzone.options.addedfile.call(myDropzone, mockFile);
    myDropzone.options.thumbnail.call(myDropzone, mockFile, "http://localhost/test/drop/uploads/banner2.jpg");
})
trushkevich
  • 2,657
  • 1
  • 28
  • 37
Marcogomesr
  • 2,614
  • 3
  • 30
  • 41
  • 3
    It is worth noting that the files added with this method behave somewhat differently from the "regular" ones. For one, I don't seem to be able to get rid of them when calling .removeAllFiles() on the dropzone instance. I posted this as a question in case someone wants to contribute: http://stackoverflow.com/questions/23369291/dropzone-js-removeallfiles-does-not-remove-mock-files – Pierlo Upitup Apr 29 '14 at 15:45
  • 9
    that's because you haven't actually added any files to the files array. Use thisDropzone.files.push(mockFile); –  Jul 06 '14 at 06:25
  • @dan where to add push function, i added below thumbnail.call but its not working. – Moxet Khan Dec 26 '15 at 16:21
  • Does this code add an existing thumbnail? Or is dropzone creating a new one on the fly? – Ian Warburton May 03 '16 at 15:56
  • 3
    The problem with this is it doesn't size down the photo to a thumbnail view, instead it just shows the top left corner of the photo.... – Justin Jul 18 '16 at 19:29
  • Do the remove link work. I tried addRemoveLinks: true but all it does for the preexisting files on server was remove it from the Dropzone and does not initiate removedfile function but works fine on the work uploaded. – Lucky Aug 19 '17 at 10:35
  • 3
    I think a better, more updated answer can be found here: https://stackoverflow.com/a/31627155/5221039 – Ryan Feb 28 '18 at 18:04
44

You can also do with the following code:

  <script>
        Dropzone.options.myAwesomeDropzone = false;
        Dropzone.autoDiscover = false;
        $("#image").dropzone({
            url: "http://someserver.com/upload.php",
            paramName: "image", // The name that will be used to transfer the file
            maxFilesize: 2, // MB
            maxFiles: 5,
            parallelUploads: 5,
            addRemoveLinks: true,
            dictMaxFilesExceeded: "You can only upload upto 5 images",
            dictRemoveFile: "Delete",
            dictCancelUploadConfirmation: "Are you sure to cancel upload?",
            accept: function (file, done) {
                console.log(file)
                if ((file.type).toLowerCase() != "image/jpg" &&
                        (file.type).toLowerCase() != "image/gif" &&
                        (file.type).toLowerCase() != "image/jpeg" &&
                        (file.type).toLowerCase() != "image/png"
                        ) {
                    done("Invalid file");
                }
                else {
                    done();
                }
            },
            init: function () {
                var mockFile = { name: "myimage.jpg", size: 12345, type: 'image/jpeg' };
                this.addFile.call(this, mockFile);
                this.options.thumbnail.call(this, mockFile, "http://someserver.com/myimage.jpg");
            }
        });
    </script>

EDIT

Since update of Dropzone 4.0 init function can be called as:

init: function () {
   var mockFile = { name: "myimage.jpg", size: 12345, type: 'image/jpeg' };       
   this.options.addedfile.call(this, mockFile);
   this.options.thumbnail.call(this, mockFile, "http://someserver.com/myimage.jpg");
   mockFile.previewElement.classList.add('dz-success');
   mockFile.previewElement.classList.add('dz-complete');
}
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
  • 2
    fwiw, i found that `addFile` errors in chrome on the latest v of dropzone, using `options.addedfile.call` worked instead – Alex Moore-Niemi Apr 12 '15 at 16:42
  • How can i cancel the removeLink on manual added file(s)? Please help – Adobe Oct 13 '15 at 20:03
  • @Adobe Can u be more specific? – Vicky Gonsalves Oct 14 '15 at 02:40
  • @Vicky Gonsalves Ok. Your solution provide to add existing files in Dropzone. I have on init event "addRemoveLinks" in TRUE. So all pre-added files with "delete link". But how to diable "romoveLink" for pre-added files? – Adobe Oct 14 '15 at 04:43
  • If you know which are the pre added files, you can always prevent it from being deleted with if.. Else... Condition – Vicky Gonsalves Oct 14 '15 at 04:46
  • @Vicky Gonsalves I can't do real delete because "removedfile" event not always executing (dunno why). I tried do like that: **this.addRemoveLinks = false;** but addRemoveLinks in TRUE – Adobe Oct 14 '15 at 05:31
24

my solution for >= 4.0, basing on "How to show files already stored on server": https://github.com/enyo/dropzone/wiki/FAQ

maxFiles: 1,

init: function () {
    this.on('maxfilesexceeded', function (file) {
        this.removeAllFiles();
        this.addFile(file);
    });

    var mocks = $dropzone.data('dropzone');
    for (var i = 0; i < mocks.length; i++) {
        var mock = mocks[i];
        mock.accepted = true;

        this.files.push(mock);
        this.emit('addedfile', mock);
        this.createThumbnailFromUrl(mock, mock.url);
        this.emit('complete', mock);
    }
}
punky
  • 381
  • 2
  • 4
  • 1
    this is the right answer in my opinion, it handles correctly the use of `resize` and `maxFiles` options – Andrei Cojea Mar 09 '16 at 16:09
  • How to specify the thumbnail style? I have created a B&W versions that I would like to show as thumbnails, how to do that? – W.M. Aug 27 '17 at 21:09
  • My problem was that thumbnail of my file was being shown partially, i was using "this.emit("thumbnail", mockFile, item.Path);" . I replaced this with "this.createThumbnailFromUrl(mock, mock.url);" and it worked. – Harry .Naeem Sep 19 '17 at 05:57
12

Based on punky's excellent answer above, you should not forget to add this._updateMaxFilesReachedClass(); at the end, like so:

init: function () {
    var mockFile = { name: <filename>, size: <filesize>, type: <filetype>, url: <file_url> };
    this.files.push(mockFile);
    this.emit('addedfile', mockFile);
    this.createThumbnailFromUrl(mockFile, mockFile.url);
    this.emit('complete', mockFile);
    this._updateMaxFilesReachedClass();
}
Oded Davidov
  • 171
  • 2
  • 6
  • 5
    In order to get it working it is necessary to set the file as accepted, otherwise the event **maxfilesreached** is not emitted (see _updateMaxFilesReachedClass code). A quick solution is to add **accepted: true** to the mockFile. What do you think? – Mauro Nidola Feb 01 '17 at 10:16
  • 5
    @MauroNidola You are right. There is no point in using `this._updateMaxFilesReachedClass();` if you do not add `accepted: true` to the mockFile. – Niket Pathak Aug 15 '17 at 21:38
7

In this answer https://stackoverflow.com/a/17763511, it's implemeneted with emmiting a thumbnail event.

Following is an example of doing it using createThumbnailFromUrl.

HTML element;

<form id="sample-img" action="/upload" class="dropzone">
    <div class="dz-default dz-message"></div>
</form>

JS code;

previewThumbailFromUrl({
    selector: 'sample-img',
    fileName: 'sampleImg',
    imageURL: '/images/sample.png'
});

function previewThumbailFromUrl(opts) {
    var imgDropzone = Dropzone.forElement("#" + opts.selector);
    var mockFile = {
        name: opts.fileName,
        size: 12345,
        accepted: true,
        kind: 'image'
    };
    imgDropzone.emit("addedfile", mockFile);
    imgDropzone.files.push(mockFile);
    imgDropzone.createThumbnailFromUrl(mockFile, opts.imageURL, function() {
        imgDropzone.emit("complete", mockFile);
    });
}

Working Samples on JSFiddle:

  1. Load images on same domain
  2. Load images with crossOrigin
Community
  • 1
  • 1
gihanchanuka
  • 4,783
  • 2
  • 32
  • 32
  • Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. – Justin Jul 18 '16 at 19:22
  • @Justin, here is a working example of my above code https://jsfiddle.net/gihanchanuka/pp66q18p/1 . Since you got a Cross-Origin issue over HTTPS doesn't mean that above code is not working for same domain image URLs. As you can clearly see through my answer `imageURL: '/images/sample.png'`, it's referring to an image which is in same domain. This is a solution which is built on my knowledge. You can seek for other solutions as well. Here is more about your Error http://stackoverflow.com/a/27840082/1461060. Hope this will help you! – gihanchanuka Jul 19 '16 at 10:11
  • @Justin I have looked into the DropzoneJS implementation https://github.com/antpaw/dropzone/blob/2a960cf89c70b0eb8b73d65fbbcc56cce9ae516f/src/dropzone.coffee#L1009 , and figured out the issue that you unable to solve. DropzoneJS is allowing to pass configuration for `crossOrigin`. Please refer to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img. I have updated the answer with `crossOrigin` option as well. https://jsfiddle.net/gihanchanuka/6gksmdrr/1/ – gihanchanuka Jul 19 '16 at 17:35
2
 var mockFile = { name: "banner2.jpg", size: 12345, uuid: "085b2b23-70e7-4175-8355-89937d8d46f2" };
 myDropzone.emit("addedfile", mockFile);
 myDropzone.options.thumbnail.call(myDropzone, mockFile, "https://your-thumbnail-image.jpg");

On Init-Function of the Dropzone-Object init: function() { call this:

this.on("addedfile", function(file) {
  //Access the preview element with file.previewElement and add event listeners, etc... to it.
  var a = document.createElement('a');
  a.setAttribute('href',"{{{protokoll}}}://{{{HTTP_HOST}}}/a-getfiledb.php?uuid="+file.uuid);
  a.setAttribute('class',"btn btn-success");
  a.setAttribute('style',"width:50%; margin-top:5px; border-left:1px solid black; cursor:pointer;");
  a.innerHTML = "<i class='glyphicon glyphicon-download-alt'></i>";
  file.previewTemplate.appendChild(a);
});
  • This code shows existing images already uploaded on the server in the Dropzone box. However, when I tried to re-upload these images, they are not recognized as being in the queue. this.getQueuedFiles().length , and myDropzone.getUploadingFiles().length both returns 0. I am using dropzone5.5.0.js. Please help. – J K Mar 07 '19 at 09:21
1

I was having hard time with this also. This one as a starting point would have helped even more:

Dropzone.autoDiscover = false; // otherwise will be initialized twice
var myDropzoneOptions = {
    maxFilesize: 5,
    addRemoveLinks: true,
    clickable: true
};
var myDropzone = new Dropzone('#myDropzoneElement', myDropzoneOptions);
var mockFile = { name: "Existing file!", size: 12345 };
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, "http://url-to-thumb-goes-here");
ux.engineer
  • 10,082
  • 13
  • 67
  • 112
-1

You can try with this

var file_image = "http://someserver.com/myimage.jpg";

var mockFile = { name: "myimage.jpg", size: 12345 };

$("#dropzone").dropzone({

    url: 'false',
    maxFiles: 1,
    maxFilesize:10,//mb
    acceptedFiles:'image/*',
    init: function() {
        this.on("addedfile", function(file){
            this.options.thumbnail.call(this,file,file_image);
         });
         this.addFile.call(this,mockFile);
    }
});
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Algoleigol
  • 161
  • 1
  • 2
  • 10
-1

 import vue2Dropzone from 'vue2-dropzone'
    import 'vue2-dropzone/dist/vue2Dropzone.min.css'
    export default {
        created(){
            let app = this;
            app.getAdvertById()
        },
         data: function () {
            return {
                advertId: null,
                advert: {
                    title: '',
                    description: '',
                    confirm: '',
                    files: {},
                    category:'',
                    city:''
                },
               
                adverts: [],
                   dropzoneOptions: {
                    url: 'https://httpbin.org/post',
                    thumbnailWidth: 150,
                    addRemoveLinks: true,
                    maxFilesize: 0.5,
                    dictDefaultMessage: 'Plz add your image here...',
                    headers: { "My-Awesome-Header": "header value" }
                },
            }
        },
          methods: {
            getAdvertById(){
                let app = this;
                let id = app.$route.params.id;
                app.advertId = id;
                axios.get('/api/v1/advert/show/' + app.advertId)
                    .then(function (resp) {
                        app.advert = resp.data
                        app.advert.files = resp.data.files
                         for (var i = 0; i < app.advert.files.length; i++) {
                            var mockFile = {id: app.advert.files[i].id, name: app.advert.files[i].file_name, size: app.advert.files[i].size};
                            app.$refs.myVueDropzone.manuallyAddFile(mockFile, '/advert/' + app.advert.files[i].file_name )
                            app.$refs.myVueDropzone.dropzone.options.thumbnail.call(app.$refs.myVueDropzone, mockFile, '/advert/' + app.advert.files[i].file_name)
                            if (app.$refs.myVueDropzone.dropzone.options.maxFiles > 0) {
                                app.$refs.myVueDropzone.dropzone.options.maxFiles--
                            }
                            }
                    })
                    .catch(function () {
                        alert("Could not load your advert")
                    });
                    //console.log(app.advert.files)
            },
          }
        }
 <vue-dropzone  ref="myVueDropzone" id="dropzone" :options="dropzoneOptions"></vue-dropzone>
  • 1
    Answers are generally better received when you add some context or explain them, instead of just dropping code. – zcoop98 Sep 15 '20 at 15:26