【问题标题】:Integrate Dropzone js in media library Wordpress在媒体库 Wordpress 中集成 Dropzone js
【发布时间】:2020-09-30 21:52:37
【问题描述】:

我被这个问题困扰并尝试了很多方法,例如:How to integrate Dropzonejs with wordpress media handler in frontend?

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

我正在 wordpress 中制作一个自定义插件,以允许在媒体库 (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,我可以裁剪图像并将其上传到我的媒体库。

我的问题是大多数管理员使用“拖放”功能。

这个拖放是由wordpress制作的,覆盖整个正文。

当我添加我的 dropzone 时,由于 wordpress dropzone,我无法将文件放入其中。

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

有什么建议或答案吗?

谢谢。

【问题讨论】:

    标签: javascript php jquery wordpress dropzone.js


    【解决方案1】:

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

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

    希望对某人有所帮助!我可以就此提出任何问题或建议。

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2021-07-12
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多