Use plupload to upload images and save them to custom folder and database table

I'm building a plugin and I need to upload images and save them to a separate folder from the default wp media folder and to a custom database table.

I managed to do both, but for every uploaded image I get a 404 error on the console and I don't think the way I did it is good.

Here is the code:

?php ?

script
(function ( $ ) {

$(document).ready(function () {
    var i = ?php echo $chapter-id; ?;
    var path = '?php echo MT_DIR_PATH . sanitize_title(get_the_title()) . '_' . $post-ID . '/ch_' . $chapter-chapter_number; ?';
    var plugin_dir = '?php echo MT_URL ?';
    var manga_id  = $('#the-post-id').val();

    function upload(i){
        var uploader = new plupload.Uploader({
            runtimes : 'html5,html4',
            browse_button : 'add-images-'+i, // you can pass in id...
            container: document.getElementById('container'), // ... or DOM Element itself
            url : plugin_dir + 'do.php',
            filters : {
                max_file_size : '10mb',
                mime_types: [
                    {title : 'Image files', extensions : 'jpg,gif,png'}
                ]
            },
            multipart_params : {
                "chapter_id": i,
                "path": path
            },
            init: {
                PostInit: function() {
                    document.getElementById('filelist-'+i).innerHTML = '';
                    document.getElementById('start-upload-'+i).onclick = function() {
                        uploader.start();
                        return false;
                    };
                },

                FilesAdded: function(up, files) {
                    plupload.each(files, function(file) {
                        document.getElementById('filelist-'+i).innerHTML += 'div id="' + file.id + '"' + file.name + ' (' + plupload.formatSize(file.size) + ') b/b/div';
                    });
                },

                UploadProgress: function(up, file) {
                    document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'span' + file.percent + "%/span";
                }
            }
        });

        uploader.init();
    }
    upload(i);

The do.php file

?php
$filename = $_FILES["file"]["name"];
$special_chars = array("?", "[", "]", "/", "\\", "=", "", "", ":", ";", ",", "'", "\"", "", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
$filename = str_replace($special_chars, '', $filename);
$filename = preg_replace('/[\s-]+/', '-', $filename);
$filename = trim($filename, '.-_');
$target_dir = $_POST['path'];
require_once("includes/PluploadHandler.php");
require( '../../../wp-blog-header.php' );

PluploadHandler::no_cache_headers();
PluploadHandler::cors_headers();
if (!PluploadHandler::handle(array(
    'target_dir' = $target_dir,
    'allow_extensions' = 'jpg,jpeg,png'
))) {
    die(json_encode(array(
        'OK' = 0,
        'error' = array(
            'code' = PluploadHandler::get_error_code(),
            'message' = PluploadHandler::get_error_message()
        )
    )));
}

    global $wpdb;
    $wpdb-insert( $wpdb-prefix . 'mt_images', array('image_name' = $filename, 'chapter_id' = $_POST['chapter_id']));
    die(json_encode(array('OK' = 1)));

Why do I get that error even though the images are uploaded and saved in the db?

Is my approach wrong?

Topic plupload plugin-development Wordpress

Category Web


I managed to do it by myself thanks to this tutorial.

Moved content of do.php file to a function named cmr_upload inside a class.

Then changed the plupload options from:

        url : plugin_dir + 'do.php',
        ...
        multipart_params : {
            "chapter_id": i,
            "path": path

to

        url : '<?php echo admin_url('admin-ajax.php') ?>',
        ...
        multipart_params : {
            "chapter_id": i,
            "path": path,
            "action": "cmr_upload"

Then added the function to an ajax action:

$this->loader->add_action('wp_ajax_cmr_upload', $plugin_admin, "cmr_upload"); 

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.