上传

时间:2017-10-13 10:51:49

标签: javascript jquery dropzone.js dropzone

我想在我的dropzone文件上传器中添加一个按钮上传。目前,在选择或拖动文件到dropzone区域后,它会直接上传文件。我想做的是: 1.选择或暂停要上载的文件。 2.验证 3.点击或按下上传按钮上传文件。

N.B:按下按钮上传后才会上传文件。

这是我的表格

<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.";
         }
      }
   }

3 个答案:

答案 0 :(得分:26)

你需要:

  1. 添加按钮:

    return nil
  2. 告知Dropzone 在删除文件时自动上传文件,默认情况下会这样。这是通过the autoProcessQueue config option完成的:

    <button type="submit" id="button" class="btn btn-primary">Submit</button>
    
  3. 由于Dropzone现在不会自动上传文件,因此您需要在单击按钮时手动告诉它执行此操作。所以你需要一个事件处理程序来点击该按钮,告诉Dropzone进行上传:

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

    refCampaignID
  5. 全部放在一起:

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

答案 1 :(得分:5)

还应该添加一个纯香草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,并且可能导致意外的副作用。只有知道自己在做什么,才应该这样做。

答案 2 :(得分:0)

对于 Vue Js

如果没有安装,请安装 vue2-dropzone

关于你想要的组件:

<div class="form-group">
                        <label for="">Product Name</label>
                        <input type="text" v-model="product_name" placeholder="Product Name" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="">Product SKU</label>
                        <input type="text" v-model="product_sku" placeholder="sku" class="form-control">
                    </div>
<div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Media</h6>
                </div>
                <div class="card-body border">
                    <vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions" v-on:vdropzone-sending="sendingEvent"></vue-dropzone>
                </div>
            </div>

保存按钮:

 <button @click="saveProduct" type="submit" class="btn btn-lg btn-primary">Save</button>

在脚本标签内

import vue2Dropzone from 'vue2-dropzone'

导入'vue2-dropzone/dist/vue2Dropzone.min.css'

 data() {
    return {
        product_name: '',
        product_sku: '',
      
        dropzoneOptions: {
            url: "/product/images",
            thumbnailWidth: 150,
            maxFilesize: 0.5,
            addRemoveLinks: true,
            autoProcessQueue:false,
            uploadMultiple:true,
            headers: {"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
        }
    }
},
methods: {
    saveProduct() {
        this.$refs.myVueDropzone.processQueue();
    },
    sendingEvent (file, xhr, formData) {
        formData.append("title", this.product_name);
        formData.append("sku", this.product_sku);
        console.log(formData);
    }

}

有关更多详细信息,请访问这些:

https://rowanwins.github.io/vue-dropzone/docs/dist/#/additionalParams

https://www.dropzonejs.com/#configuration-options

GitHub 问题: https://github.com/rowanwins/vue-dropzone/issues/476