如何在前端将Dropzonejs与wordpress媒体处理程序集成? [英] How to integrate Dropzonejs with wordpress media handler in frontend?

查看:155
本文介绍了如何在前端将Dropzonejs与wordpress媒体处理程序集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dropzonejs是一个非常广泛的JavaScript库,提供了很多选项来处理媒体上传。

为了整合dropzonejs和wordpress,这个过程非常简单。假设下面这段代码就是您要上传的地方。

 < div id =media-uploaderclass = 悬浮窗 >< / DIV> 
< input type =hiddenname =media-idsvalue =>

有一个类 dropzone 会自动附加与元素的dropzone事件。这将阻止我们覆盖默认参数。因此,我们希望禁用库的自动发现功能。

  //禁用autoDiscover,否则Dropzone会尝试连接两次。 
Dropzone.autoDiscover = false;

现在我们将使用 jQuery
$ b

  jQuery(#media-uploader)。dropzone({
url:dropParam。 upload,
acceptedFiles:'image / *',
success:function(file,response){
file.previewElement.classList.add(dz-success);
文件['attachment_id'] =响应; / /推的ID以备将来参考
var ids = jQuery('#media-ids')。val()+','+ response;
jQuery '#media-ids')。val(ids);
},
error:function(file,response){
file.previewElement.classList.add(dz-error) ;
},
//更新以下部分用于从库中移除图像
addRemoveLinks:true,
removedfile:function(file){
var attachment_id = file .attachment_id;
jQuery.ajax({
type:'POST',
url:dropParam.del ete,
data:{
media_id:attachment_id
}
});
var _ref;
return(_ref = file.previewElement)!= null? _ref.parentNode.removeChild(file.previewElement):void 0;
}
});

在上面的代码中,我们已经将dropzone与我们的元素附加了一些参数 - p>


  • url - 我们要发送文件上传的位置。稍后我会初始化这个变量。

  • acceptedFiles - 因为我们只对上传图片感兴趣,所以我们将文件限制为仅附加到图像。你可以在这个库的网站上找到更多。

  • 成功 - 上载文件/图片时触发的回调成功。它接受两个参数,上传文件本身的参考和来自服务器的响应。这是非常重要的,在这里我们存储附件id在我们的形式。您可以在存储该ID之前执行验证。

  • addRemoveLinks - 在预览面板下方添加删除文件链接,您可以使用CSS来设置样式。

  • removedfile - 处理操作,当您点击删除文件预览面板。在这个函数中,我们发送了一个 ajax 调用到我们的服务器,以从库中删除图像


    当然有很多选项可用,但是我发现这些是我设置拖放式媒体上传器所需的最基本的参数。

    现在最重要的是要决定文件上传网址。您可以在自己想要处理操作的位置拥有自定义文件。但是我找到了另一种方法。



    从这个问题和答案我发现使用 admin-post.php 文件是相当了不起的。



    很多人抱怨这个 admin-post.php ,所以认为坚持 wp_ajax.php drophandler 变量,如下所示:

    -

      wp_enqueue_script('dropzone','path / to / dropzone',array('jquery')); 
    wp_enqueue_script('my-script','path / to / script',array('jquery','dropzone'));
    $ drop_param = array(
    'upload'=> admin_url('wp_ajax.php?action = handle_dropped_media'),
    'delete'=> admin_url('wp_ajax.php?action = handle_deleted_media'),

    wp_localize_script('my-script','dropParam',$ drop_param);

    现在我们准备将图像发送到服务器。在这里,我们将在主题的 function.php 文件或插件文件中添加一些 php 代码,但是我们需要以确保它被加载。

    下面的函数将负责上传图像并作为附件保存在库中。

      add_action('wp_ajax_handle_dropped_media','BMP_handle_dropped_media'); 

    //如果您想允许您的网站访问者上传文件,请谨慎。
    add_action('wp_ajax_nopriv_handle_dropped_media','BMP_handle_dropped_media');



    函数BMP_handle_dropped_media(){
    status_header(200);

    $ upload_dir = wp_upload_dir();
    $ upload_path = $ upload_dir ['path']。 DIRECTORY_SEPARATOR;
    $ num_files = count($ _ FILES ['file'] ['tmp_name']);

    $ newupload = 0;

    if(!empty($ _ FILES)){
    $ files = $ _FILES;
    foreach($ files as $ file){
    $ newfile = array(
    'name'=> $ file ['name'],
    'type'=> $ file ['type'],
    'tmp_name'=> $ file ['tmp_name'],
    'error'=> $ file ['error'],
    'size '=> $ file ['size']
    );

    $ _FILES = array('upload'=> $ newfile);
    foreach($ _ FILES as $ file => $ array){
    $ newupload = media_handle_upload($ file,0);
    }
    }
    }

    echo $ newupload;
    die();



    $ b $ p
    $ b

    以下操作负责删除媒体元素。 wp_delete_attachment()函数的第二个参数允许我们决定是要清理图像还是完全删除图像。我想完全删除它,所以通过 true

      add_action(' admin_post_handle_delete_media','BMP_handle_delete_media'); 

    函数BMP_handle_delete_media(){

    if(isset($ _ REQUEST ['media_id'])){
    $ post_id = absint($ _REQUEST ['media_id' ]);

    $ status = wp_delete_attachment($ post_id,true);
    $ b $ if($ status)
    echo json_encode(array('status'=>'OK'));
    else
    echo json_encode(array('status'=>'FAILED'));
    }

    die();



    $ b $ p $这将返回 attachment_id media_handle_upload($ file,0); 中,我传递了文件的引用和一个 0 (0为没有帖子,但是如果你想分配,那么在这里传递帖子ID。更多的引用在 codex 中。)



    这是在wordpress上传媒体的全部内容。注意:我还没有完成删除上传的文件的部分。 我会马上完成这个工作。

    更新

    该帖子已更新。现在我们可以从上传容器中删除上传的媒体元素。感谢这个问题和答案我可以认为拿出实际的过程。

    How can I integrate Dropzonejs file uploader library in wordpress front end just like the built in one and have the uploaded one available in my media library?

    解决方案

    Dropzonejs is a very extensive javascript library that provides a lot of options to handle media uploading.

    To integrate dropzonejs with wordpress the process is pretty straight forward. Assume the following piece of code is where you want to appear your uploader.

    <div id="media-uploader" class="dropzone"></div>
    <input type="hidden" name="media-ids" value="">
    

    Having a class dropzone will automatically attach the dropzone event with the element. That will stop us from overriding default parameters. So we would like to disable the auto discover feature of the library.

    // Disabling autoDiscover, otherwise Dropzone will try to attach twice.
    Dropzone.autoDiscover = false;
    

    Now we will use jQuery to bind our configuration with the element.

    jQuery("#media-uploader").dropzone({
        url: dropParam.upload,
        acceptedFiles: 'image/*',
        success: function (file, response) {
            file.previewElement.classList.add("dz-success");
            file['attachment_id'] = response; // push the id for future reference
            var ids = jQuery('#media-ids').val() + ',' + response;
            jQuery('#media-ids').val(ids);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        },
        // update the following section is for removing image from library
        addRemoveLinks: true,
        removedfile: function(file) {
            var attachment_id = file.attachment_id;        
            jQuery.ajax({
                type: 'POST',
                url: dropParam.delete,
                data: {
                    media_id : attachment_id
                }
            });
            var _ref;
            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;        
        }
    });
    

    In the code above what we have done is we attached dropzone with our element with some parameters-

    • url - location where we want to send our files to upload. I'll initialize the variable later.
    • acceptedFiles - since we are only interested in uploading images, we will limit the files to be attached only to images. You can find about more in the website of this library.
    • success - a callback that is fired when the file/image is uploaded successfully. It accepts two parameter the reference of the uploaded file itself and the response from the server. This is very important, here we stored the attachment id in our form. You can perform a validation here prior to store the id.
    • error - if the file failed to upload then you can perform any task here.
    • addRemoveLinks - add the remove file link below the preview panel, you can style it with your css.
    • removedfile - handles the operation while you click on the remove file link for an image in the preview panel. In this function we sent an ajax call to our server to remove the image from the library

    Of course there are a lot of option available, but I found these are the most basic parameters I required to setup my drag-n-drop media uploader.

    Now the most important thing is to decide about the file uploader url. You can have a custom file where you would want to process the operation. But I found another way.

    From this question and the answer I found using admin-post.php file is pretty amazing.

    Many people complained about this admin-post.php, so think sticking to the wp_ajax.php is the best option.

    So I initialized the drophandler variable prior to my dropzone initialization as follows-

    wp_enqueue_script('dropzone','path/to/dropzone', array('jquery'));
    wp_enqueue_script('my-script','path/to/script',array('jquery','dropzone'));
    $drop_param = array(
      'upload'=>admin_url( 'wp_ajax.php?action=handle_dropped_media' ),
      'delete'=>admin_url( 'wp_ajax.php?action=handle_deleted_media' ),
    )
    wp_localize_script('my-script','dropParam', $drop_param);
    

    Now we are ready to send our images to the server. Here we will add some php code whether in the theme's function.php file or in our plugin file, but we need to be assured that it is loaded.

    The following function will take care of the uploading the image and saving as an attachment in the library.

    add_action( 'wp_ajax_handle_dropped_media', 'BMP_handle_dropped_media' );
    
    // if you want to allow your visitors of your website to upload files, be cautious.
    add_action( 'wp_ajax_nopriv_handle_dropped_media', 'BMP_handle_dropped_media' );
    
    
    
    function BMP_handle_dropped_media() {
        status_header(200);
    
        $upload_dir = wp_upload_dir();
        $upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
        $num_files = count($_FILES['file']['tmp_name']);
    
        $newupload = 0;
    
        if ( !empty($_FILES) ) {
            $files = $_FILES;
            foreach($files as $file) {
                $newfile = array (
                        'name' => $file['name'],
                        'type' => $file['type'],
                        'tmp_name' => $file['tmp_name'],
                        'error' => $file['error'],
                        'size' => $file['size']
                );
    
                $_FILES = array('upload'=>$newfile);
                foreach($_FILES as $file => $array) {
                    $newupload = media_handle_upload( $file, 0 );
                }
            }
        }
    
        echo $newupload;    
        die();
    }
    

    The following action take care of the deletion of the media element. Second parameter of wp_delete_attachment() function allows us to decide whether we want to trash the image or completely delete it. I wanted to delete it completely so passed true.

    add_action( 'admin_post_handle_delete_media', 'BMP_handle_delete_media' );
    
    function BMP_handle_delete_media(){
    
        if( isset($_REQUEST['media_id']) ){
            $post_id = absint( $_REQUEST['media_id'] );
    
            $status = wp_delete_attachment($post_id, true);
    
            if( $status )
                echo json_encode(array('status' => 'OK'));
            else
                echo json_encode(array('status' => 'FAILED'));
        }
    
        die();
    }
    

    This will return the attachment_id in the response and we'll get it in the success function. In the media_handle_upload( $file, 0 ); I passed the reference of the file and a 0 because I didn't wanted to assign the media with any post yet (0 for no post, but if you want to assign then pass the post ID here. More reference in the codex.)

    This is all for uploading media in wordpress.

    Note: I haven't completed the removing uploaded file part. I'll complete this in a moment.

    UPDATE

    The post is updated. Now we can remove uploaded media elements from the uploader container. Thanks to this question and the answer I could figure out the actual process.

    这篇关于如何在前端将Dropzonejs与wordpress媒体处理程序集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆