简体   繁体   English

Dropzone并上传到多个文件夹

[英]Dropzone and upload to multiple folders

Hello, I'm looking for a way to upload files to folders. 您好,我正在寻找一种将文件上传到文件夹的方法。

I have a dropzone on the website where I can put all files and then upload it. 我在网站上放置了一个dropzone,可以在其中放置所有文件,然后上传。 But what I need is to choose which file to which folder. 但是我需要选择哪个文件到哪个文件夹。

I want to add 3rd button (select option) to which folder upload it. 我想将第三个按钮(选择选项)添加到哪个文件夹上载它。 Probably using the onChange event. 可能使用onChange事件。

Any idea how to do it only for that only one file ? 任何想法只对一个文件怎么做?

Example: 例:

body.png START CANCEL FOLDER (images) - when i press start, it will upload to images folder body.png开始取消文件夹(图像)-当我按开始时,它将上传到图像文件夹

styles.css START CANCEL FOLDER (css) - when i press start, it will upload to css folder styles.css开始取消文件夹(css)-当我按开始时,它将上传到css文件夹

Upload script: 上传脚本:

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
} else {
  echo "Invalid file";
}
?>

Dropzone script: Dropzone脚本:

<script>
      var previewNode = document.querySelector("#template");
      previewNode.id = "";
      var previewTemplate = previewNode.parentNode.innerHTML;
      previewNode.parentNode.removeChild(previewNode);

      var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
        url: "upload.php", // Set the url
        thumbnailWidth: 80,
        thumbnailHeight: 80,
        parallelUploads: 20,
        previewTemplate: previewTemplate,
        autoQueue: false, // Make sure the files aren't queued until manually added
        previewsContainer: "#previews", // Define the container to display the previews
        clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
      });

      myDropzone.on("addedfile", function(file) {
        // Hookup the start button
        file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
      });

      // Update the total progress bar
      myDropzone.on("totaluploadprogress", function(progress) {
        document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
      });

      myDropzone.on("sending", function(file) {
        // Show the total progress bar when upload starts
        document.querySelector("#total-progress").style.opacity = "1";
        // And disable the start button
        file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
      });

      // Hide the total progress bar when nothing's uploading anymore
      myDropzone.on("queuecomplete", function(progress) {
        document.querySelector("#total-progress").style.opacity = "0";
      });

      // Setup the buttons for all transfers
      // The "add files" button doesn't need to be setup because the config
      // `clickable` has already been specified.
      document.querySelector("#actions .start").onclick = function() {
        myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
      };
      document.querySelector("#actions .cancel").onclick = function() {
        myDropzone.removeAllFiles(true);
      };
    </script>

AND the body construct: AND主体构造:

<body>

  <div class="container" id="container">
    <h1>Dropzone.js</h1>
    <br>
    <br>
    <div id="actions" class="row">

      <div class="col-lg-7">
        <!-- The fileinput-button span is used to style the file input field as button -->
        <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Add files...</span>
        </span>
        <button type="submit" class="btn btn-primary start">
            <i class="glyphicon glyphicon-upload"></i>
            <span>Start upload</span>
        </button>
        <button type="reset" class="btn btn-warning cancel">
            <i class="glyphicon glyphicon-ban-circle"></i>
            <span>Cancel upload</span>
        </button>

      </div>

      <div class="col-lg-5">
        <!-- The global file processing state -->
        <span class="fileupload-process">
          <div id="total-progress" 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>
        </span>
      </div>

    </div>

    <div class="table table-striped" class="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>
            <strong class="error text-danger" data-dz-errormessage></strong>
        </div>
        <div>
            <p class="size" data-dz-size></p>
            <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>
          <button class="btn btn-primary start">
              <i class="glyphicon glyphicon-upload"></i>
              <span>Start</span>
          </button>
          <button data-dz-remove class="btn btn-warning cancel">
              <i class="glyphicon glyphicon-ban-circle"></i>
              <span>Cancel</span>
          </button>
          <button data-dz-remove class="btn btn-danger delete">
            <i class="glyphicon glyphicon-trash"></i>
            <span>Delete</span>
          </button>
        </div>
      </div>

    </div>

(Proof of concept only, needs much refinement, validation and security measures.) (仅概念验证,需要大量改进,验证和安全措施。)

This sets up a dropzone that requires the "Submit all files" button to be clicked before upload starts. 这将设置一个放置区,要求在开始上载之前单击“提交所有文件”按钮。 When a file is added to the dropzone a select list with folder names is loaded along with the file preview. 将文件添加到放置区后,带有文件夹名称的选择列表将随文件预览一起加载。 Select a folder name for each upload item, then click the submit button. 为每个上传项目选择一个文件夹名称,然后单击提交按钮。 The files are uploaded and each one gets directed into the folder that is designated by it's corresponding folder select list. 文件被上传,每个文件都直接进入相应文件夹选择列表所指定的文件夹。

form.html form.html

<button id="submit-all">Submit all files</button>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>

<script>

Dropzone.options.myDropzone = {

  // Prevents Dropzone from uploading dropped files immediately
  autoProcessQueue: false,

  init: function() {
    var submitButton = document.querySelector("#submit-all"),
        myDropzone = this; // closure

    submitButton.addEventListener("click", function() {
      myDropzone.processQueue(); // Tell Dropzone to process all queued files
    });

    this.on('addedfile', function(file) {
        var select = document.createElement('select');
        select.setAttribute('name', 'folder[' + file.name + ']');

        var option;
        option = document.createElement('option');
        option.innerHTML = 'images';
        select.appendChild(option);

        option = document.createElement('option');
        option.innerHTML = 'css';
        select.appendChild(option);

        document.forms[0].appendChild(select);
    });
  }
};

</script>

upload.php upload.php

<?php

if (!empty($_FILES)) {
    $filename = $_FILES['file']['name'];
    $fp = ( isset($_POST['folder'][$filename]) )? $_POST['folder'][$filename]: '';
    $folder = ( 'images' == $fp || 'css' == $fp )? $fp: 'upload';

    move_uploaded_file(
        $_FILES['file']['tmp_name'],
        dirname( __FILE__ ) . '/' . $folder . '/' . $filename
    );
}
else { echo 'error: no file'; }

?>

A side note: it's apparent that dropzone causes an XHR action for each file that is uploaded. 旁注:很明显dropzone会对上传的每个文件造成XHR操作。 Therefore every element in the form, including every select list, gets appended to the formData object of the XHR for every file uploaded, resulting in redundancy. 因此,表单中的每个元素(包括每个选择列表)都会针对每个上载的文件附加到XHR的formData对象中,从而导致冗余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM