如何使用Dropzone.js展示已存储在服务器上的文件

66

我不理解那个... call 总是未定义的。

创建模拟文件:

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

调用默认的 addedfile 事件处理程序

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

并且可以选择显示文件的缩略图:

myDropzone.options. thumbnail.call(myDropzone, mockFile, "/image/url");

创建缩略图的参数在版本> 5中已更改。要使其再次正常工作,请查看此GitHub Issue: https://github.com/enyo/dropzone/issues/1587#issuecomment-324023260 - Paul Beck
9个回答

48

终于!!

$(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");
})

3
值得注意的是,使用此方法添加的文件与“常规”文件的行为有些不同。首先,当调用删除区实例的 .removeAllFiles() 方法时,我似乎无法摆脱它们。如果有人想要贡献,我已将此发布为一个问题:https://dev59.com/in_aa4cB1Zd3GeqP0DRl - Pierlo Upitup
9
这是因为您实际上还没有将任何文件添加到文件数组中。请使用 thisDropzone.files.push(mockFile)。 - user963714
这段代码是添加现有的缩略图吗?还是Dropzone会即时创建一个新的缩略图? - Ian Warburton
3
问题在于它没有将照片缩小为缩略图视图,而只是显示照片的左上角。 - Justin
3
我认为这里可以找到一个更好、更更新的答案:https://dev59.com/qI3da4cB1Zd3GeqPzGX6#31627155。 - Ryan
显示剩余2条评论

44

你也可以使用以下代码:

  <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>

编辑

自Dropzone 4.0更新后,init函数可以这样调用:

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');
}

2
就我所知,我发现在最新版本的Dropzone中,在Chrome浏览器中使用addFile会出错,而使用options.addedfile.call则可以解决问题。 - Alex Moore-Niemi
如何取消手动添加的文件上的removeLink?请帮忙。 - Adobe
@Adobe 能否更具体一些? - Vicky Gonsalves
@Vicky Gonsalves 好的。您提供的解决方案可以在Dropzone中添加现有文件。我在初始化事件中设置了"addRemoveLinks"为TRUE。因此,所有预先添加的文件都带有"删除链接"。但是如何禁用预添加文件的"romoveLink"? - Adobe
如果您知道哪些是预添加的文件,您可以始终使用if..else..条件来防止其被删除。 - Vicky Gonsalves
@Vicky Gonsalves 我无法进行真正的删除,因为"removedfile"事件并不总是执行(不知道为什么)。我尝试像这样做:this.addRemoveLinks = false; 但是addRemoveLinks却是TRUE。 - Adobe

24

基于"How to show files already stored on server",我的解决方案适用于 >= 4.0版本: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);
    }
}

1
在我看来,这是正确的答案,它正确处理了resizemaxFiles选项的使用。 - Andrei Cojea
如何指定缩略图样式?我已经创建了黑白版本,想要将其显示为缩略图,该怎么做? - W.M.
我的问题是文件的缩略图只显示了一部分,我之前使用的是“this.emit("thumbnail", mockFile, item.Path);”。我将其替换为“this.createThumbnailFromUrl(mock, mock.url);”,结果解决了问题。 - Harry .Naeem

12

根据punky的优秀回答,你不应忘记在结尾处添加 this._updateMaxFilesReachedClass(); ,像这样:

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();
}

5
为使其正常工作,需要将该文件设置为已接受状态,否则事件“maxfilesreached”不会被触发(请参见_updateMaxFilesReachedClass代码)。一个快速的解决方案是在模拟文件中添加“accepted: true”。你怎么看? - Mauro Nidola
5
你说得对。如果你没有在模拟文件中添加“accepted: true”,使用this._updateMaxFilesReachedClass();是没有意义的。 - Niket Pathak

7
在这个答案https://dev59.com/SmMm5IYBdhLWcg3wO9Ly#17763511中,它是通过发射一个缩略图事件来实现的。
以下是使用createThumbnailFromUrl进行操作的示例。
HTML元素:
<form id="sample-img" action="/upload" class="dropzone">
    <div class="dz-default dz-message"></div>
</form>

JS代码;

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);
    });
}

JSFiddle上的工作示例:

  1. 在同一域名下加载图像
  2. 使用crossOrigin加载图像

未捕获的安全错误:CanvasRenderingContext2D上的 'getImageData' 执行失败:画布已被跨源数据污染。 - Justin
@Justin,这是我上面代码的一个工作示例 https://jsfiddle.net/gihanchanuka/pp66q18p/1。由于您在HTTPS上遇到了跨域问题,并不意味着上面的代码不能用于相同域名的图像URL。正如您可以清楚地看到我的答案中 imageURL: '/images/sample.png',它引用的是同一域中的图像。这是基于我的知识构建的解决方案。您也可以寻找其他解决方案。这里有关于您的错误的更多信息 https://dev59.com/yWEh5IYBdhLWcg3wvFbY#27840082。希望这能帮助到您! - gihanchanuka
@Justin,我已经研究了DropzoneJS的实现 https://github.com/antpaw/dropzone/blob/2a960cf89c70b0eb8b73d65fbbcc56cce9ae516f/src/dropzone.coffee#L1009,并找出了你无法解决的问题。DropzoneJS允许传递`crossOrigin`配置,请参考https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img。我也更新了答案,加入了`crossOrigin`选项。https://jsfiddle.net/gihanchanuka/6gksmdrr/1/ - gihanchanuka

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");

在 Dropzone 对象的 Init 函数中 init: function() { 调用 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);
});

这段代码展示了在Dropzone框中已上传到服务器的现有图片。然而,当我尝试重新上传这些图片时,它们无法被识别为队列中的内容。this.getQueuedFiles().length和myDropzone.getUploadingFiles().length都返回0。我正在使用dropzone5.5.0.js,请帮忙解决。 - J K

1

我也曾经遇到过这个问题。如果有一个起点,会更加有帮助:

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");

-1

你可以试试这个

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);
    }
});

-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
当你添加一些上下文或解释时,答案通常会更受欢迎,而不仅仅是放置代码。 - zcoop98

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接