上传时的 Dropzone 提交按钮

IT技术 javascript jquery dropzone.js dropzone
2021-03-12 00:03:18

我想向我的 dropzone 文件上传器添加一个按钮上传。目前它是在选择文件或将文件拖入拖放区区域后直接上传文件。我想要做的是: 1. 选择或拖放要上传的文件。2. 验证 3. 点击或按下上传按钮上传文件。

注意:文件只有在按下上传按钮后才被上传。

这是我的表格

<form id='frmTarget' name='dropzone' action='upload_files.php' class='dropzone'>
   <div class='fallback'>
      <input name='file' type='file' multiple />
   </div>
   <input id='refCampaignID' name='refCampaignID' type='hidden' value=\ "$rowCampaign->CampaignID\" />
</form>

这是我的 JS

Dropzone.options.frmTarget = 
    {
            url: 'upload_files.php',
            paramName: 'file',
            clickable: true,
            maxFilesize: 5,
            uploadMultiple: true, 
            maxFiles: 2,
            addRemoveLinks: true,
            acceptedFiles: '.png,.jpg,.pdf',
            dictDefaultMessage: 'Upload your files here',
            success: function(file, response)
            {
                setTimeout(function() {
                    $('#insert_pic_div').hide();
                    $('#startEditingDiv').show();
                }, 2000);
            }
        };

这是我的 php 帖子请求

 foreach ($_FILES["file"] as $key => $arrDetail) 
   {
      foreach ($arrDetail as $index => $detail) {
         //print_rr($_FILES["file"][$key][$index]);
         $targetDir = "project_images/";
         $fileName = $_FILES["file"]['name'][$index];
         $targetFile = $targetDir.$fileName;

         if(move_uploaded_file($_FILES["file"]['tmp_name'][$index],$targetFile))
         {
            $db = new ZoriDatabase("tblTarget", $_REQUEST["TargetID"], null, 0);
            $db->Fields["refCampaignID"] = $_REQUEST["refCampaignID"];
            $db->Fields["strPicture"] = $fileName;
            $db->Fields["blnActive"] = 1;
            $db->Fields["strLastUser"] = $_SESSION[USER]->USERNAME;
            $result = $db->Save();

            if($result->Error == 1){
               return "Details not saved.";
            }else{
               return "Details saved.";
            }
         }else{
            return "File not uploaded.";
         }
      }
   }
2个回答

你需要:

  1. 添加按钮:

    <button type="submit" id="button" class="btn btn-primary">Submit</button>
    
  2. 告诉 Dropzone在您放下文件时不要自动上传文件,因为默认情况下它会这样做这是通过配置选项完成autoProcessQueue

    autoProcessQueue: false
    
  3. 由于 Dropzone 现在不会自动上传文件,因此您需要在单击按钮时手动告诉它这样做。所以你需要一个按钮点击的事件处理程序,它告诉 Dropzone 进行上传:

    $("#button").click(function (e) {
        e.preventDefault();
        myDropzone.processQueue();
    });
    
  4. 这只会发布上传的文件,没有任何其他输入字段。您可能想要发布所有字段,例如您的refCampaignID,CSRF 令牌(如果您有的话)等等。为此,您需要在发送之前将它们复制到 POST 中。Dropzone 有一个在发送每个文件之前调用sending事件,您可以在其中添加回调:

    this.on('sending', function(file, xhr, formData) {
        // Append all form inputs to the formData Dropzone will POST
        var data = $('form').serializeArray();
        $.each(data, function(key, el) {
            formData.append(el.name, el.value);
        });
    });
    

把它们放在一起:

Dropzone.options.frmTarget = {
    autoProcessQueue: false,
    url: 'upload_files.php',
    init: function () {

        var myDropzone = this;

        // Update selector to match your button
        $("#button").click(function (e) {
            e.preventDefault();
            myDropzone.processQueue();
        });

        this.on('sending', function(file, xhr, formData) {
            // Append all form inputs to the formData Dropzone will POST
            var data = $('#frmTarget').serializeArray();
            $.each(data, function(key, el) {
                formData.append(el.name, el.value);
            });
        });
    }
}
autoProcessQueue属性前添加标头后修复了 csrf-token 令牌问题headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
2021-04-21 00:03:18
是的,这很完美,但是如果我们想要进行服务器端验证怎么办。如果出现验证错误,队列将为空
2021-04-25 00:03:18
@Udara 答案的第 4 步显示了代码,该代码将包含 POSTed 数据中表单中的所有输入。如果您的表单中有 CSRF 字段,它将被发送 - 无需也将其添加为标题。
2021-05-06 00:03:18
我该如何发送“csrf-token”?
2021-05-11 00:03:18
之前如何更新文件 myDropzone.processQueue();
2021-05-13 00:03:18

还以为我会添加一个纯香草 JS 解决方案,没有 jQuery。

/* 'dropform' is a camelized version of your dropzone form's ID */
      Dropzone.options.dropform = {
        /* Add all your configuration here */
        autoProcessQueue: false,

        init: function()
        {
          let myDropzone = this;
          /* 'submit-dropzone-btn' is the ID of the form submit button */
          document.getElementById('submit-dropzone-btn').addEventListener("click", function (e) {
              e.preventDefault();
              myDropzone.processQueue();
          });

          this.on('sending', function(file, xhr, formData) 
          {
            /* OPTION 1 (not recommended): Construct key/value pairs from inputs in the form to be sent off via new FormData
               'dropform' is the ID of your dropzone form
               This method still works, but it's submitting a new form instance.  */
              formData = new FormData(document.getElementById('dropform'));

             /* OPTION 2: Append inputs to FormData */
              formData.append("input-name", document.getElementById('input-id').value);
          });
        }
      };

注意:设置事件侦听器(例如sending我们在这里所做的)应该放在init函数中。如果您要将它们放在其他地方,例如:

init: function() 
{
    //...
},
sending: function(file, xhr, formData) 
{
  //... logic before each file send
}

这将覆盖为sending事件侦听器提供的默认逻辑 dropzone ,并可能导致意外的副作用。只有当您知道自己在做什么时,才应该这样做。