在媒体库 Wordpress 中集成 Dropzone js

Integrate Dropzone js in media library Wordpress

我被那个问题困住了并尝试了很多事情,比如:How to integrate Dropzonejs with wordpress media handler in frontend?

但是我在任何地方都找不到答案所以这就是问题:

我正在 wordpress 中制作自定义插件以允许 crop/resize/optimize 进入媒体库 (upload.php)。

PHP

<?php
/*
Plugin name: Waouh_pictures
Description: bla bla bla
Version: 1.0
Author: Waouh
*/

if(!defined('ABSPATH'))
exit;

class plugin{
  public function __construct(){

    /* Adding script and style */
    function add_custom_script_admin() {
      wp_enqueue_script('croppie_script', '/wp-content/plugins/waouh_pictures/js/croppie.js', array('jquery'), false);
      wp_enqueue_script('dropzone_pictures_script', '/wp-content/plugins/waouh_pictures/js/dropzone.js', array('jquery'), false);
      wp_enqueue_script('waouh_pictures_script', '/wp-content/plugins/waouh_pictures/js/waouh_pictures.js', array('jquery'), false);
      wp_enqueue_style('croppie_style', '/wp-content/plugins/waouh_pictures/css/croppie.css');
      wp_enqueue_style('dropzone_style', '/wp-content/plugins/waouh_pictures/css/dropzone.css');
      wp_enqueue_style('waouh_pictures_style', '/wp-content/plugins/waouh_pictures/css/waouh_pictures.css');
      $data = array(
        'upload_url' => admin_url('async-upload.php'),
        'ajax_url'   => admin_url('admin-ajax.php'),
        'nonce'      => wp_create_nonce('media-form')
      );
      wp_localize_script( 'waouh_pictures_script', 'su_config', $data );
    }

    add_action( 'admin_enqueue_scripts', 'add_custom_script_admin' );

    /* Removing wordpress thumbnails */
    function remove_default_image_sizes( $sizes ) {
      unset( $sizes[ 'thumbnail' ]);
      unset( $sizes[ 'medium' ]);
      unset( $sizes[ 'medium_large' ]);
      unset( $sizes[ 'large' ]);
      unset($sizes[ '1536x960' ]);
      return $sizes;
    }

    add_filter( 'intermediate_image_sizes_advanced', 'remove_default_image_sizes', 99 );
  }
}
new plugin();
?>

JavaScript

jQuery(document).ready(function($){
  // Replacement of the original wordpress button by my custom form
  $("#wp-media-grid > a").after("<form action=\"\" method=\"post\" class=\"image-form dropzone\"><input type=\"file\" id=\"button_upload_waouh\" name=\"async-upload\" class=\"image-file\" accept=\"image/*\" required><input type=\"hidden\" id=\"imagebase64\" name=\"imagebase64\"><input id=\"submit_button\" type=\"submit\" value=\"Valider\"></form>");
  $("#wp-media-grid > a").hide();
  $("#button_upload_waouh").after("<div id=\"upload-demo\"></div>");
  // Hidding image preview when there is no image selected
  $("#upload-demo").hide();

  Dropzone.autoDiscover = false;

  // Adding croppie to crop/resize image
  demoUpload();
  function demoUpload() {
    var $uploadCrop;

    function readFile(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
          $('#upload-demo').addClass('ready');
          $uploadCrop.croppie('bind', {
            url: e.target.result
          }).then(function(){
            console.log('jQuery bind complete');
          });

        }

        reader.readAsDataURL(input.files[0]);
      }
      else {
        swal("Sorry - you're browser doesn't support the FileReader API");
      }
    }

    // Parameters of croppie
    $uploadCrop = $('#upload-demo').croppie({
      viewport: {
        width: 200,
        height: 200,
        type: 'circle'
      },
      boundary: {
        width: 300,
        height: 300
      },
      enableExif: true
    });

    // Function to convert Base64 into File
    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    }

    // Preview the selected image on change
    $('#button_upload_waouh').on('change', function () { readFile(this); });

    // Show the preview on click
    $('#button_upload_waouh').on('click', function(){ $("#upload-demo").show(); });

    // When the form is submit by the user
    $('#submit_button').on('click', function (ev) {
      // Calling ajax
      ev.preventDefault();
      $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'original',
        format: 'png'
      }).then(function (resp) {
        // resp is in base64 type so I keep the name and convert it to file type
        var base_name = resp.split(';')[0];
        var mime = base_name.split('/')[1];
        var filename = "image." + mime;
        var $imgForm    = $('.image-form');
        var $imgFile    = dataURLtoFile(resp, filename);
        var $imgId      = $imgForm.find('[name="image_id"]');
        var $submit     = $('#submit_button');
        // Creating formData to submit data (calling ajax and wordpress admin php)
        var formData = new FormData();
        formData.append('action', 'upload-attachment');
        formData.append('async-upload', $imgFile);
        formData.append('name', $imgFile.name);
        formData.append('_wpnonce', su_config.nonce);
        // Ajax request
        $.ajax({
          url: su_config.upload_url, // http://yoursite.com/wp-admin/async-upload.php
          data: formData, // Our formData with all data
          processData: false,
          contentType: false,
          dataType: 'json',
          type: 'POST',
          success: function(result) {
            console.log(result); // Showing in console the result
          }
        });
        $("#upload-demo").hide();
      });
    });
  }
});

我也有一个 css 样式表,但实际上什么都没有。

此代码有效,感谢 croppie,我可以裁剪图像并将其上传到我的媒体库。

我的问题是大多数管理员使用 "drag and drop" 功能。

这个拖拽是wordpress做的,包罗万象

当我添加我的拖放区时,由于 wordpress 拖放区,我无法将文件拖放到其中。

我不想调整 body 的大小,我希望允许我的 dropzone 在 body 内工作。

有什么建议或答案吗?

谢谢。

好吧,我在我的问题上做了很多工作,我终于找到了解决方案! 只是给你我的代码,因为我做了很多改变,我不记得我做了什么,但它有效!我在代码中有很多评论,所以我相信你们可以阅读我的代码。

PHP

<?php
/*
Plugin name: Waouh_pictures
Description: 
Version: 1.0
Author: Waouh
*/

if(!defined('ABSPATH'))
exit;

class plugin{
  public function __construct(){

    /* Adding script and style */
    function add_custom_script_admin() {
      wp_enqueue_script('croppie_script', '/wp-content/plugins/waouh_pictures/js/croppie.js', array('jquery'), false);
      wp_enqueue_script('dropzone_pictures_script', '/wp-content/plugins/waouh_pictures/js/dropzone.js', array('jquery'), false);
      wp_enqueue_script('waouh_pictures_script', '/wp-content/plugins/waouh_pictures/js/waouh_pictures.js', array('jquery'), false);
      wp_enqueue_style('croppie_style', '/wp-content/plugins/waouh_pictures/css/croppie.css');
      wp_enqueue_style('dropzone_style', '/wp-content/plugins/waouh_pictures/css/dropzone.css');
      wp_enqueue_style('waouh_pictures_style', '/wp-content/plugins/waouh_pictures/css/waouh_pictures.css');
      $data = array(
        'upload_url' => admin_url('async-upload.php'),
        'ajax_url'   => admin_url('admin-ajax.php'),
        'nonce'      => wp_create_nonce('media-form')
      );
      wp_localize_script( 'waouh_pictures_script', 'su_config', $data );
    }

    add_action( 'admin_enqueue_scripts', 'add_custom_script_admin' );

    /* Removing wordpress thumbnails */
    function remove_default_image_sizes( $sizes ) {
      unset( $sizes[ 'thumbnail' ]);
      unset( $sizes[ 'medium' ]);
      unset( $sizes[ 'medium_large' ]);
      unset( $sizes[ 'large' ]);
      unset($sizes[ '1536x960' ]);
      return $sizes;
    }

    add_filter( 'intermediate_image_sizes_advanced', 'remove_default_image_sizes', 99 );
  }
}
new plugin();
?>

JS

jQuery(document).ready(function($){
  // Replacement of the original button wordpress by my custom form
  $("#wp-media-grid > a").after("<form action=\"\" method=\"post\" class=\"image-form dropzone\"><input type=\"file\" id=\"button_upload_waouh\" name=\"async-upload\" class=\"image-file\" accept=\"image/*\" required><input id=\"submit_button\" type=\"submit\" value=\"Valider\"></form>");
  $("#wp-media-grid > a").hide();
  $("#button_upload_waouh").after("<div id=\"upload-demo\"></div>");
  // Hidding image preview when there is no image selected
  $("#upload-demo").hide();

  Dropzone.autoDiscover = false;

  // Adding croppie to crop/resize image
  demoUpload();
  function demoUpload() {
    var $uploadCrop;

    function readFile(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e){
          $('#upload-demo').addClass('ready');
          $uploadCrop.croppie('bind', {
            url: e.target.result
          }).then(function(){
            console.log('jQuery bind complete');
          });

        }
        reader.readAsDataURL(input.files[0]);
      }
      else {
        console.log("Sorry - you're browser doesn't support the FileReader API");
      }
    }

    // Parameters of croppie
    $uploadCrop = $('#upload-demo').croppie({
      viewport: {
        width: 200,
        height: 200,
        type: 'circle'
      },
      boundary: {
        width: 300,
        height: 300
      },
      enableExif: true
    });

    // Function to convert Base64 into File
    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    }

    // Preview the selected image on change
    $('#button_upload_waouh').on('change', function () { readFile(this); });

    // Show the preview on click
    $('#button_upload_waouh').on('click', function(){ $("#upload-demo").show(); });

    $(".dropzone").dropzone({
      url: 'async-upload.php',
      autoProcessQueue: false,
      uploadMultiple: false,
      acceptedFiles: "image/*",
      init: function (){
        this.on("addedfile", function (file){
          $("#upload-demo").show();
          if(file){
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e){
              $('#upload-demo').addClass('ready');
              $uploadCrop.croppie('bind', {
                url: e.target.result
              }).then(function(){
                console.log('jQuery bind complete');
              });
            }
          } else {
            console.log("No files detected");
          }
        });
      }
    });

    // When the form is submit by the user
    $('#submit_button').on('click', function (ev) {
      // Calling ajax
      ev.preventDefault();
      $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'original',
        format: 'png'
      }).then(function (resp){
        // resp is in base64 type so I keep the name and convert it to file type
        var base_name = resp.split(';')[0];
        var mime = base_name.split('/')[1];
        var filename = "image." + mime;
        var $imgForm    = $('.image-form');
        var $imgFile    = dataURLtoFile(resp, filename);
        var $imgId      = $imgForm.find('[name="image_id"]');
        var $submit     = $('#submit_button');
        // Creating formData to submit data (calling ajax and wordpress admin php)
        var formData = new FormData();
        formData.append('action', 'upload-attachment');
        formData.append('async-upload', $imgFile);
        formData.append('name', $imgFile.name);
        formData.append('_wpnonce', su_config.nonce);
        // Ajax request
        $.ajax({
          url: su_config.upload_url, // http://yoursite.com/wp-admin/async-upload.php
          data: formData, // Our formData with all data
          processData: false,
          contentType: false,
          dataType: 'json',
          type: 'POST',
          success: function(result) {
            console.log(result); // Showing in console the result
          }
        });
        $("#upload-demo").hide();
      });
    });
  }
});

CSS

.uploader-window{
  display: none !important;
}

.dz-preview, dz-image-preview{
  display: none !important;
}

希望对某人有所帮助!我随时准备就此提出任何问题或建议。