【问题标题】:How to add text input to dropzone upload如何将文本输入添加到 dropzone 上传
【发布时间】:2013-12-21 20:53:11
【问题描述】:

我想允许用户为每个拖入 Dropzone 的文件提交一个标题,该文件将被输入到文本输入中。但我不知道如何添加它。大家可以帮帮我吗?

这是我的html代码代码

  <form id="my-awesome-dropzone" class="dropzone">
  <div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->

  <!-- Now setup your input fields -->
  <input type="email" name="username" id="username" />
  <input type="password" name="password" id="password" />

  <button type="submit">Submit data and files!</button>
</form>

这是我的脚本代码

<script>
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element

  // The configuration we've talked about above
  url: "upload.php",
  autoProcessQueue: false,
  uploadMultiple: true,
  parallelUploads: 100,
  maxFiles: 100,
  maxFilesize:10,//MB

  // The setting up of the dropzone
  init: function() {
    var myDropzone = this;

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
      // Make sure that the form isn't actually being sent.
      e.preventDefault();
      e.stopPropagation();
      myDropzone.processQueue();
    });

    // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
    // of the sending event because uploadMultiple is set to true.
    this.on("sendingmultiple", function() {
      // Gets triggered when the form is actually being sent.
      // Hide the success button or the complete form.

    });
    this.on("successmultiple", function(files, response) {
      // Gets triggered when the files have successfully been sent.
      // Redirect user or notify of success.

    });
    this.on("errormultiple", function(files, response) {
      // Gets triggered when there was an error sending the files.
      // Maybe show form again, and notify user of error
    });
  },
  accept: function (file, done) {
        //maybe do something here for showing a dialog or adding the fields to the preview?
    },
 addRemoveLinks: true
}
</script>  

【问题讨论】:

  • 你找到解决办法了吗?如果有,请分享!

标签: templates upload custom-fields dropzone.js


【解决方案1】:

您实际上可以为 Dropzone 提供一个模板来呈现图像预览以及任何额外的字段。在您的情况下,我建议您使用默认模板或制作您自己的模板,然后在此处添加输入字段:

<div class="dz-preview dz-file-preview">
    <div class="dz-image"><img data-dz-thumbnail /></div>
    <div class="dz-details">
        <div class="dz-size"><span data-dz-size></span></div>
        <div class="dz-filename"><span data-dz-name></span></div>
    </div>
    <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
    <div class="dz-error-message"><span data-dz-errormessage></span></div>
    <input type="text" placeholder="Title">
</div>

完整的默认预览模板可以在dropzone.js的源代码中找到。


然后,您可以简单地将自定义模板作为选项参数的 previewTemplate 键的字符串传递给 Dropzone。例如:

var myDropzone = new Dropzone('#yourId', {
    previewTemplate: "..."
});

只要你的元素是一个表单,Dropzone 就会自动在 xhr 请求参数中包含所有输入。

【讨论】:

  • 这完全回答了问题。只需将他使用的 html 模板添加到 javascript 中的“previewTemplate”部分即可!
【解决方案2】:

我正在做一些非常相似的事情。我通过添加一个带有 jquery 的模式对话框来完成它,该对话框在添加文件时打开。希望对您有所帮助。

 this.on("addedfile", function() { 
   $("#dialog-form").dialog("open"); 
 });

【讨论】:

  • 一切都与它有关。我的解决方案与 OP 要求的略有不同,我很清楚这一点。但是 OP 应该能够使用相同的包装器将他们想要的任何 html 附加到添加的文件中。要么,要么他们可以进入 dropzone 并自己进行大量更改,以尝试将其作为库的标准部分破解。我最初是自己开始走这条路的,这更容易。
【解决方案3】:

在我的回答中,用您的“标题”字段替换我的“描述”字段。

将输入文本或文本区域添加到预览模板。例如:

<div class="table table-striped files" id="previews">

  <div id="template" class="file-row">
    <!-- This is used as the file preview template -->
    <div>
        <span class="preview"><img data-dz-thumbnail /></span>
    </div>
    <div>
        <p class="name" data-dz-name></p>
        <input class="text" type="text" name="description" id="description" placeholder="Searchable Description">
    </div>  ... etc.
  </div>
</div>

然后在发送函数中,追加关联数据:

myDropzone.on("sending", function(file, xhr, formData) {

  // Get and pass description field data
    var str = file.previewElement.querySelector("#description").value;
    formData.append("description", str);
    ...
});

最后,在执行实际上传的处理脚本中,从 POST 接收数据:

$description = (isset($_POST['description']) && ($_POST['description'] <> 'undefined')) ? $_POST['description'] : '';

您现在可以将您的描述(或标题或您有什么)存储在数据库等中。

希望这对你有用。想不通是个混蛋。

【讨论】:

  • 感谢 Manto 的编辑。我的第一个答案。你做得更好了!
【解决方案4】:

这有点隐藏在文档中,但添加额外数据的地方是在“发送”事件中。在发送每个文件之前调用发送事件,并获取 xhr 对象和 formData 对象作为第二和第三个参数,因此您可以修改它们。

所以基本上你会想要添加这两个额外的参数,然后在“sending”函数或在你的情况下是“sendingmultiple”中附加额外的数据。您可以使用 jQuery 或纯 js 来获取值。所以它应该看起来像:

this.on("sendingmultiple", function(file, xhr, formData) {
      //Add additional data to the upload
      formData.append('username', $('#username').val());
      formData.append('password', $('#password').val());       
    });

【讨论】:

  • 唯一的问题是您无权访问事件目标,因此如果您按模板进行输入,则无法轻松获取关联元素。
【解决方案5】:

这是我的解决方案:

Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", { 
    url: 'yourUploader.php',
    init: function () {
        this.on(
            "addedfile", function(file) {
              caption = file.caption == undefined ? "" : file.caption;
              file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
              file._captionBox = Dropzone.createElement("<input id='"+file.filename+"' type='text' name='caption' value="+caption+" >");
              file.previewElement.appendChild(file._captionLabel);
              file.previewElement.appendChild(file._captionBox);
        }),
        this.on(
            "sending", function(file, xhr, formData){
            formData.append('yourPostName',file._captionBox.value);
        })
  }
});

yourUploader.php:

<?php 
  // Your Dropzone file named 
  $myfileinfo = $_POST['yourPostName'];
  // And your files in $_FILES
?>

【讨论】:

  • 附加多个请求假设一个上传多个文件并且您必须显示每个文件的描述formData.append('description[]',file._captionBox.value);
【解决方案6】:

对于那些想要保持自动并发送数据(如 ID 或不依赖于用户的东西)的人,您可以将 setTimeout 添加到“addedfile”:

myDropzone.on("addedfile", function(file) {
    setTimeout(function(){
        myDropzone.processQueue();
    }, 10);
});

【讨论】:

    【解决方案7】:

    好吧,我找到了适合我的解决方案,所以我将把它写下来,希望它也可以帮助其他人。基本方法是在预览容器中有一个新的输入,如果文件数据是通过成功的上传过程或在初始化时从现有文件传入的,则通过 css 类进行设置。

    您必须将以下代码集成到您的代码中。我只是跳过了一些可能需要让它工作的行。

    photowolke = {
        render_file:function(file)
        {
        caption = file.title == undefined ? "" : file.title;
        file.previewElement.getElementsByClassName("title")[0].value = caption;
        //change the name of the element even for sending with post later
        file.previewElement.getElementsByClassName("title")[0].id = file.id + '_title';
        file.previewElement.getElementsByClassName("title")[0].name = file.id + '_title';
        },
        init: function() {
            $(document).ready(function() {
                var previewNode = document.querySelector("#template");
                previewNode.id = "";
                var previewTemplate = previewNode.parentNode.innerHTML;
                previewNode.parentNode.removeChild(previewNode);
                photowolke.myDropzone = new Dropzone("div#files_upload", {
                    init: function() {
                        thisDropzone = this;
                        this.on("success", function(file, responseText) {
                            //just copy the title from the response of the server
                            file.title=responseText.photo_title;
                            //and call with the "new" file the renderer function
                            photowolke.render_file(file);
                        });
                        this.on("addedfile", function(file) {
                           photowolke.render_file(file);
                        });
                    },
                    previewTemplate: previewTemplate,
                });
                //this is for loading from a local json to show existing files
                $.each(photowolke.arr_photos, function(key, value) {
                    var mockFile = {
                        name: value.name,
                        size: value.size,
                        title: value.title,
                        id: value.id,
                        owner_id: value.owner_id
                    };
                    photowolke.myDropzone.emit("addedfile", mockFile);
                    // And optionally show the thumbnail of the file:
                    photowolke.myDropzone.emit("thumbnail", mockFile, value.path);
                    // Make sure that there is no progress bar, etc...
                    photowolke.myDropzone.emit("complete", mockFile);
                });
            });
        },
    };
    

    还有我的预览模板:

     <div class="dropzone-previews" id="files_upload" name="files_upload"> 
             <div id="template" class="file-row">
        <!-- This is used as the file preview template -->
        <div>
            <span class="preview"><img data-dz-thumbnail width="150" /></span>
        </div>
        <div>
        <input type="text" data-dz-title class="title" placeholder="title"/>
    
            <p class="name" data-dz-name></p><p class="size" data-dz-size></p>
            <strong class="error text-danger" data-dz-errormessage></strong>
        </div>
        <div>
    
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
              <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
            </div>
        </div>
    
    
      </div>
    

    【讨论】:

      【解决方案8】:
      $("#my-awesome-dropzone").dropzone({
          url: "Enter your url",
          uploadMultiple: true,
          autoProcessQueue: false,
      
          init: function () {
              let totalFiles = 0,
                  completeFiles = 0;
              this.on("addedfile", function (file) {
                  totalFiles += 1;
                  localStorage.setItem('totalItem',totalFiles);
                  caption = file.caption == undefined ? "" : file.caption;
                  file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
                  file._captionBox = Dropzone.createElement("<textarea rows='4' cols='15' id='"+file.filename+"' name='caption' value="+caption+" ></textarea>");
                  file.previewElement.appendChild(file._captionLabel);
                  file.previewElement.appendChild(file._captionBox);
                  // this.autoProcessQueue = true;
              });
              document.getElementById("submit-all").addEventListener("click", function(e) {
                  // Make sure that the form isn't actually being sent.
                  const myDropzone = Dropzone.forElement(".dropzone");
                  myDropzone.processQueue();
              });
              this.on("sending", function(file, xhr, formData){
                  console.log('total files is '+localStorage.getItem('totalItem'));
                      formData.append('description[]',file._captionBox.value);
              })
      
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-28
        • 2016-07-09
        • 1970-01-01
        • 2012-03-23
        • 2015-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多