【问题标题】:Dropzone.js - Display existing files on serverDropzone.js - 显示服务器上的现有文件
【发布时间】:2014-07-23 10:37:08
【问题描述】:

我目前正在使用 dropzone.js v3.10.2 我在显示我已上传的现有文件时遇到问题。我精通 php,但是在 ajax 和 js 方面我的知识有限

如果你能帮忙就太好了

提前致谢

index.php

    <html>

<head>  

<link href="css/dropzone.css" type="text/css" rel="stylesheet" />


<script src="ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script src="dropzone.min.js"></script>

<script>

Dropzone.options.myDropzone = {
    init: function() {
        thisDropzone = this;

        $.get('upload.php', function(data) {


            $.each(data, function(key,value){

                var mockFile = { name: value.name, size: value.size };

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

                thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/"+value.name);

            });

        });
    }
};
</script>

</head>

<body>


<form action="upload.php" class="dropzone" id="my-dropzone"></form>

</body>

上传.php

<?php
$ds          = DIRECTORY_SEPARATOR; 

$storeFolder = 'uploads';  

if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];         

    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; 

    $targetFile =  $targetPath. $_FILES['file']['name']; 

    move_uploaded_file($tempFile,$targetFile);

} else {                                                           
    $result  = array();

    $files = scandir($storeFolder);                 //1
    if ( false!==$files ) {
        foreach ( $files as $file ) {
            if ( '.'!=$file && '..'!=$file) {       //2
                $obj['name'] = $file;
                $obj['size'] = filesize($storeFolder.$ds.$file);
                $result[] = $obj;
            }
        }
    }

    header('Content-type: text/json');              //3
    header('Content-type: application/json');
    echo json_encode($result);
}
?>

PS。我知道 php 正在检索数据

提前致谢

达米安

【问题讨论】:

  • 嗨 Damian,我检查了最新版本的 jquery 1.x 的代码(来自 startutorial),我看到了一个错误。您是否尝试过使用 firebug 或询问编写 tut 的人?

标签: php ajax image dropzone.js


【解决方案1】:

我检查了代码(来自 startTutorial),但它对我也不起作用(?)

我设法通过替换它来让它工作:

$.get('upload.php', function(data) {
  $.each(data, function(key,value) {
    var mockFile = { name: value.name, size: value.size };
    thisDropzone.options.addedfile.call(thisDropzone, mockFile);
    thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/"+value.name);
  });
});

用这个:

$.getJSON('files/list-all', function(data) {
  $.each(data, function(index, val) {
    var mockFile = { name: val.name, size: val.size };
    thisDropzone.options.addedfile.call(thisDropzone, mockFile);
    thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/" + val.name);
  });
});

感谢这个答案:https://stackoverflow.com/a/5531883/984975

编辑: 在 4.0 版中,现有文件的缩略图将在其中显示提示栏。为了解决这个添加:

thisDropzone.emit("complete", mockFile);

【讨论】:

  • 我想建议像 StarTutorial 建议的那样将上传的文件及其原始名称保留在用户本地驱动程序上是一种非常不负责任的做法。文件通常会被覆盖一个。
  • 缩略图是否在您的应用程序中正确调整大小?我有麻烦。 ://
  • 是的,它运行良好。到底发生了什么?
  • imgur.com/zDcYMHb.jpg 左边的图片是重新加载的,右边的图片是刚刚上传的。也许它是一种类型,会重做几次代码,也许我会找到错误。也许一些不同的 jQuery 版本...
  • @zehelvion 问题通过让 Dropzone 下载并通过函数 myDropzone.createThumbnailFromUrl(file,imageurl) 调整大小来解决。谢谢
【解决方案2】:

对于 Dropzone 5.x

目前给出的解决方案不适用于 dropzone 版本 5.x。 对我有用的是修改 dropzone 的配置选项,如下所示:

init: function () {
                var mockFile = {
                    name: 'FileName',
                    size: '1000', 
                    type: 'image/jpeg',
                    accepted: true            // required if using 'MaxFiles' option
                };
                this.files.push(mockFile);    // add to files array
                this.emit("addedfile", mockFile);
                this.emit("thumbnail", mockFile, 'http://url/to/file');
                this.emit("complete", mockFile); 
            }

概念是,创建一个模拟文件,并调用事件处理程序addedfilethumbnail来绘制预览。然后最后调用complete事件,确保没有进度条等显示出来。

Reference

【讨论】:

  • 谢谢 - 这对我有用!您知道在提交表单时如何使用这些图像吗?当我提交表单时,只会将新添加的图像发送到服务器。
  • @Chris。不客气。只有新图像会被发送到服务器,因为您通过 init() 显示的文件是一个模拟文件(并且它已经存在于您的服务器上)
  • @NiketPathak 不确定我是否了解这如何获取先前已上传到 url 文件夹的 3 个文件。我每个属性都有一个文件夹,然后将上传的文件放在那里。不确定它如何读取该文件夹的内容并填充 DZ?
  • @justdan0227 这不会读取文件夹内容。需要提供这些信息的是您。例如,在 PHP 中,您可以读取相关目录,准备 mockFile 对象,然后直接在 javascript 中回显。这就是 DZ 了解已上传文件的方式。
  • 这是我的解决方案:github.com/dropzone/dropzone/issues/443#issuecomment-905357585 受此解决方案的启发。
【解决方案3】:

我将把对我有用的解决方案留在这里。 (Dropzone v5.7.0 和 Codeigniter v3.1.11)

  1. 使用 Dropzone 选项初始化
  2. 对后端脚本进行 AJAX 调用,该脚本返回包含图像信息的 json 编码对象数组(问题中为 PHP 方式,此处为 Codeigniter 方式)
  3. 使用 jQuery 每个函数迭代每个包含图像信息的对象
  4. 在此处使用 sn-p:https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server 显示每张图片

在我的应用控制器中:

public function ilan_fotolari($ilan_id = 0)
{
    $this->load->helper('ilan');
    $dirPath = './assets/uploads/'.ilan_dir($ilan_id);
    $this->load->helper('file');
    $file_names = get_filenames($dirPath);
    $mocks = [];
    foreach ($file_names as $file_name) {
        $mock['name'] = $file_name;
        $dirUrl = base_url('assets/uploads/'.ilan_dir($ilan_id));
        $mock['url'] = $dirUrl.$file_name;
        $mocks[] = $mock;
    }
    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($mocks));
}

在我的 script.js 中:

Dropzone.options.ilanFotoAlani = {
    paramName: "foto", // The name that will be used to transfer the file
    maxFilesize: 5, // MB
    maxFiles: 9,
    resizeWidth: 1000,
    resizeHeight: 644,
    resizeMimeType: 'image/jpeg',
    addRemoveLinks: true,
    dictDefaultMessage: 'Fotoğraf sürükle veya seç',
    dictFileTooBig: 'Fotoğraf boyutu en fazla 5MB olmalı',
    dictRemoveFile: 'Fotoğrafı sil',
    dictCancelUpload: 'İptal et',
    dictMaxFilesExceeded: 'En fazla 9 fotoğraf yükleyebilirsin',
    init: function () {
        let myDropzone = this;
        $.ajax({
            type: 'get',
            url: '/ilan-fotolari',
            success: function(mocks){
                $.each(mocks, function(key,value) {
                    let mockFile = { name: value.name, size: 1024 };
                    myDropzone.displayExistingFile(mockFile, value.url);
                });
            },
            error: function(xhr, durum, hata) {
                alert("Hata: " + hata);
            }
        });
    }
};

我将不同解决方案的解决方案混在一起。

【讨论】:

    【解决方案4】:

    这是我实现它的方式。我使用 createThumbnailFromUrl 而不是发出 thumbnail 事件。

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

    【讨论】:

      【解决方案5】:

      我遇到了 maxFiles/maxfilesexceeded 的问题,在寻找 anwser 时花了一些时间,然后我在下面找到了这个链接:

      https://www.bountysource.com/issues/1444854-use-files-already-stored-on-server-wiki-example-incomplete?utm_campaign=plugin&utm_content=tracker%2F283989&utm_medium=issues&utm_source=github

      $.each(obj, function(i, item) {
      
        ///faking the BytesSent its not essanail to me.. if you need it just pass the correct one
        var upload = {bytesSent: 12345};
      
        /// again fake the size..
        var mockFile = {name: item.name, size: 12345, accepted: true};
      
        mockFile.upload = upload;
        mockFile.kind = "file";
        Dropzone.forElement("#editfileuploader").emit("addedfile", mockFile);
      
        //push the file to files array because getAcceptedFiles using this array length to get the currct files count..
        Dropzone.forElement("#editfileuploader").files.push(mockFile);
      
        //this for lettig dropzone to creat the thumbnail(item.ts has the file location)
        Dropzone.forElement("#editfileuploader").emit("thumbnail", mockFile, item.ts);
      
        //to show the success mark and to return image id response
        Dropzone.forElement("#editfileuploader").emit("success", mockFile, item.id);
      }); 
      

      【讨论】:

      • 成功后我也发出完成:Dropzone.forElement("#editfileuploader").emit("complete", mockFile)
      【解决方案6】:

      新的更新

      这是一个老问题,但在 Dropzone 的最新版本中,更准确地说,从 5.7.0 版本开始,可以轻松显示现有文件 通过名为displayExistingFile 的专用方法。

      示例

      let myDropzone = new Dropzone("div#myId", { 
          url: "/file/post"
      });
      
      const files = [
          {name: 'square-600', size: 1000, url: 'https://via.placeholder.com/600'},
          {name: 'square-800', size: 1200, url: 'https://via.placeholder.com/800'}
      ];
      
      files.forEach(function (file) {
      
          let mockFile = {
              name: file.name,
              size: file.size,
          };
      
          myDropzone.displayExistingFile(mockFile, file.url);
      });
      

      displayExistingFile 的类型定义

      displayExistingFile(
          mockFile: Dropzone.DropzoneMockFile,
          imageUrl: string,
          callback?: () => void,
          crossOrigin?: 'anonymous' | 'use-credentials',
          resizeThumbnail?: boolean,
      ): any;
      

      【讨论】:

        猜你喜欢
        • 2015-10-16
        • 2013-07-19
        • 2016-12-25
        • 1970-01-01
        • 2016-09-10
        • 2016-10-11
        • 1970-01-01
        • 2018-07-27
        • 2013-07-01
        相关资源
        最近更新 更多