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

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

问题描述

如何在 wordpress 前端集成 Dropzonejs 文件上传库,就像内置的一样,并在我的媒体库中提供上传的文件?

解决方案

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

将 dropzonejs 与 wordpress 集成的过程非常简单.假设以下代码段是您要显示上传器的位置.

<input type="hidden" name="media-ids" value="">

拥有类 dropzone 将自动将 dropzone 事件与元素关联.这将阻止我们覆盖默认参数.所以我们想禁用库的自动发现功能.

//禁用自动发现,否则 Dropzone 会尝试附加两次.Dropzone.autoDiscover = false;

现在我们将使用 jQuery 将我们的配置与元素绑定.

jQuery("#media-uploader").dropzone({网址:dropParam.upload,接受的文件:'图像/*',成功:功能(文件,响应){file.previewElement.classList.add("dz-success");文件['attachment_id'] = 响应;//推送 id 以供将来参考var ids = jQuery('#media-ids').val() + ',' + response;jQuery('#media-ids').val(ids);},错误:函数(文件,响应){file.previewElement.classList.add("dz-error");},//更新以下部分用于从库中删除图像addRemoveLinks: 真,删除的文件:函数(文件){var attach_id = file.attachment_id;jQuery.ajax({类型:'POST',网址:dropParam.delete,数据: {media_id : 附件 ID}});无功_ref;返回 (_ref = file.previewElement) != null ?_ref.parentNode.removeChild(file.previewElement) : void 0;}});

在上面的代码中,我们所做的是将 dropzone 与带有一些参数的元素-

  • url - 我们要将文件发送到上传的位置.稍后我将初始化该变量.
  • acceptedFiles - 因为我们只对上传图片感兴趣,所以我们将限制文件只附加到图片.您可以在该图书馆的网站上找到更多信息.
  • success - 成功上传文件/图像时触发的回调.它接受两个参数,上传文件本身的引用和来自服务器的响应.这很重要,这里我们将附件 id 存储在我们的表单中.您可以在存储 ID 之前在此处执行验证.
  • error - 如果文件上传失败,那么您可以在此处执行任何任务.
  • addRemoveLinks - 在预览面板下方添加删除文件链接,您可以使用 css 对其进行样式设置.
  • removedfile - 在您单击预览面板中图像的 remove file 链接时处理操作.在这个函数中,我们向我们的服务器发送了一个 ajax 调用以从库中删除图像

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

现在最重要的是决定文件上传器的 url.您可以有一个自定义文件来处理操作.但我找到了另一种方法.

从这个问题和答案我发现使用 admin-post.php 文件非常棒.

很多人抱怨这个admin-post.php,所以认为坚持使用wp_ajax.php是最好的选择.

所以我在 dropzone 初始化之前初始化了 drophandler 变量,如下所示-

wp_enqueue_script('dropzone','path/to/dropzone', array('jquery'));wp_enqueue_script('my-script','path/to/script',array('jquery','dropzone'));$drop_param = 数组('上传'=> admin_url( 'admin-ajax.php?action=handle_dropped_media' ),'delete'=>admin_url('admin-ajax.php?action=handle_deleted_media'),)wp_localize_script('my-script','dropParam', $drop_param);

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

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

add_action('wp_ajax_handle_dropped_media', 'handle_dropped_media');//如果您想允许您网站的访问者上传文件,请小心.add_action('wp_ajax_nopriv_handle_dropped_media', 'handle_dropped_media');函数handle_dropped_media() {status_header(200);$upload_dir = wp_upload_dir();$upload_path = $upload_dir['path'] .目录_分隔符;$num_files = count($_FILES['file']['tmp_name']);$newupload = 0;如果(!空($_FILES)){$文件 = $_FILES;foreach($files as $file) {$newfile = 数组 ('名称' =>$file['name'],'类型' =>$文件['类型'],'tmp_name' =>$file['tmp_name'],'错误' =>$file['错误'],'尺寸' =>$文件['大小']);$_FILES = array('上传'=>$newfile);foreach($_FILES as $file => $array) {$newupload = media_handle_upload( $file, 0 );}}}回声 $newupload;死();}

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

add_action('wp_ajax_handle_deleted_media', 'handle_deleted_media');函数handle_deleted_media(){if( isset($_REQUEST['media_id'])){$post_id = absint( $_REQUEST['media_id']);$status = wp_delete_attachment($post_id, true);如果($状态)echo json_encode(array('status' => 'OK'));别的echo json_encode(array('status' => 'FAILED'));}死();}

这将在响应中返回 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( 'admin-ajax.php?action=handle_dropped_media' ),
  'delete'=>admin_url( 'admin-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', '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', 'handle_dropped_media' );



function 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( 'wp_ajax_handle_deleted_media', 'handle_deleted_media' );

function handle_deleted_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天全站免登陆