Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Upload images and save them to custom folder and database table with plupload

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #240506
    fbg
    Participant

    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

        &lt;?php
        $filename = $_FILES["file"]["name"];
        $special_chars = array("?", "[", "]", "/", "\\", "=", "&lt;", "&gt;", ":", ";", ",", "'", "\"", "&amp;", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
        $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' =&gt; $target_dir,
            'allow_extensions' =&gt; 'jpg,jpeg,png'
        ))) {
            die(json_encode(array(
                'OK' =&gt; 0,
                'error' =&gt; array(
                    'code' =&gt; PluploadHandler::get_error_code(),
                    'message' =&gt; PluploadHandler::get_error_message()
                )
            )));
        }
    
            global $wpdb;
            $wpdb-&gt;insert( $wpdb-&gt;prefix . 'mt_images', array('image_name' =&gt; $filename, 'chapter_id' =&gt; $_POST['chapter_id']));
            die(json_encode(array('OK' =&gt; 1)));
    

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

    Is my approach wrong?

    #240531
    fbg
    Participant

    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-&gt;loader-&gt;add_action('wp_ajax_cmr_upload', $plugin_admin, "cmr_upload");

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.