WordPress AJAX文件上传-前端

时间:2015-08-16 作者:hootsmctoots84

所以我一直在阅读WordPress前端的AJAX文件上传教程。目前我什么都没用。对我来说最有意义的是:http://theaveragedev.com/wordpress-files-ajax/

这是我的代码:

在我的模板文件示例中。php

<script>var ajax_url = "<?php echo admin_url(\'admin-ajax.php\'); ?>"</script>
<form id="file_form">
    <?php wp_nonce_field(\'ajax_file_nonce\', \'security\'); ?>
    <input type="hidden" name="action" value="my_file_upload">
    <label for="file_upload">It\'s a file upload...</label>
    <input type="file" name="file_upload">
    <input type="submit" value="Go">
</form>
这是在ajax文件上传中。js公司

jQuery(document).ready(function(){
    var form_data = {};
    $(this).find(\'input\').each(function(){
        form_data[this.name] = $(this).val();
    });
    $(\'#file_form\').ajaxForm({
        url: ajax_url, // there on the admin side, do-it-yourself on the front-end
        data: form_data,
        type: \'POST\',
        contentType: \'json\',
        success: function(response){
            alert(response.message);
        }
    });
});
这是我的职责。php

function q_scripts(){
    $src = get_template_directory_uri().\'/js/ajax-file-upload.js\';
    wp_enqueue_script(\'my_ajax_file_uploader_thing\', $src, array(\'jquery\', \'jquery-form\'));
}
add_action(\'init\', \'q_scripts\');

function handle_file_upload(){
    check_ajax_referer(\'ajax_file_nonce\', \'security\');

    if(!(is_array($_POST) && is_array($_FILES) && defined(\'DOING_AJAX\') && DOING_AJAX)){
        return;
    }

    if(!function_exists(\'wp_handle_upload\')){
        require_once(ABSPATH . \'wp-admin/includes/file.php\');
    }
    $upload_overrides = array(\'test_form\' => false);

    $response = array();

    foreach($_FILES as $file){
        $file_info = wp_handle_upload($file, $upload_overrides);

        // do something with the file info...
        $response[\'message\'] = \'Done!\';
    }

    echo json_encode($response);
    die();
}

add_action(\'wp_ajax_my_file_upload\', \'handle_file_upload\');
我尝试将enctype添加到表单元素中,但没有成功。我不断收到的错误是一个警告,说“未定义”。有人知道我如何纠正这个问题吗?

EDIT

“未定义”问题现在已经消失了,因为我编辑了js文件,使其具有一个click事件,并更改了表单输入循环的选择器:

jQuery(document).ready(function($){
    $(\'#file_form :submit\').click(function() {
        var form_data = {};
        $(\'#file_form\').find(\'input\').each(function () {
            form_data[this.name] = $(this).val();
        });
        console.log(form_data);
        $(\'#file_form\').ajaxForm({
            url: ajax_url, // there on the admin side, do-it-yourself on the front-end
            data: form_data,
            type: \'POST\',
            contentType: \'json\',
            success: function (response) {
                alert(response.message);
            },
            error: function (response) {
                console.log(\'error\');
            }
        });
        return false;
    });
});
文件仍没有上载到媒体文件夹。我还想得到上传的URL后,它已经上传回来。

我正在向控制台写入file对象,以便查看正在发生的情况。下面是一个例子:

Object {security: "e6db2a6eee", _wp_http_referer: "/chat?sessionappid=138", action: "my_file_upload", file_upload: "C:\\fakepath\\download.jpg", "": "Go"}
这有什么问题吗?这就是为什么它没有上传的原因吗?

3 个回复
SO网友:Adnan Limdiwala

您好,您已经将此代码用于WordPress前端AJAX文件上载教程代码这是我的代码:

在我的模板文件示例中。php

<form enctype="multipart/form-data">
   <input type="text" name="support_title" class="support-title">
   <input type="file" id="sortpicture" name="upload">
   <input class="save-support" name="save_support" type="button" value="Save">
 </form>
这是在ajax文件上传中。js公司

      jQuery(document).on(\'click\', \'.save-support\', function (e) {

                        var supporttitle = jQuery(\'.support-title\').val();

                        var querytype = jQuery(\'.support-query\').val();
                        var file_data = jQuery(\'#sortpicture\').prop(\'files\')[0];

                        var form_data = new FormData();
                        if (supporttitle == \'\') {
                            jQuery(\'.support-title\').css({"border": "1px solid red"})
                            return false;
                        } else {
                            jQuery(\'.support-title\').css({"border": "1px solid #e3ecf0"})
                        }

                        form_data.append(\'file\', file_data);
                        form_data.append(\'action\', \'md_support_save\');
                        form_data.append(\'supporttitle\', supporttitle);

                        jQuery.ajax({
                            url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
                            type: \'post\',
                            contentType: false,
                            processData: false,
                            data: form_data,
                            success: function (response) {
                                jQuery(\'.Success-div\').html("Form Submit Successfully")
                            },  
                            error: function (response) {
                             console.log(\'error\');
                            }

                        });
                    });

                });
这是函数。PHP代码

  add_action( \'wp_ajax_md_support_save\',\'md_support_save\' );
  add_action( \'wp_ajax_nopriv_md_support_save\',\'md_support_save\' );


  function md_support_save(){
       $support_title = !empty($_POST[\'supporttitle\']) ? 
       $_POST[\'supporttitle\'] : \'Support Title\';

        if (!function_exists(\'wp_handle_upload\')) {
           require_once(ABSPATH . \'wp-admin/includes/file.php\');
       }
      // echo $_FILES["upload"]["name"];
      $uploadedfile = $_FILES[\'file\'];
      $upload_overrides = array(\'test_form\' => false);
      $movefile = wp_handle_upload($uploadedfile, $upload_overrides);

    // echo $movefile[\'url\'];
      if ($movefile && !isset($movefile[\'error\'])) {
         echo "File Upload Successfully";
    } else {
        /**
         * Error generated by _wp_handle_upload()
         * @see _wp_handle_upload() in wp-admin/includes/file.php
         */
        echo $movefile[\'error\'];
    }
    die();
 }

SO网友:Asha

HTML

<form id="article_form" name="article_form" class="wordpress-ajax-form" method="post" action="<?php echo admin_url(\'admin-ajax.php\'); ?>" enctype="multipart/form-data" >
          <input type="file" name="uploadedfiles" id="uploadedfiles"  accept="image/*"  >
          <br>
          <input type="hidden" name="action" value="custom_action">
          <br>
          <button>Send</button>
       </form>

JS

 $(".wordpress-ajax-form").submit(function(evt){  

  evt.preventDefault();
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: $(\'#article_form\').attr(\'action\'),
    type: \'POST\',
    data: formData,
    async: true,
    cache: false,
    contentType: false,
    enctype: \'multipart/form-data\',
    processData: false,
    success: function (response) {
    // alert(response);
    alert(\'Article created Successfully!!!\');
    }
  });
  return false;
  });  
SO网友:Rakesh Shah

所有功能代码。php

<小时>

if (!empty($_POST) || (!empty($_FILES))) {
    require_once (ABSPATH . \'/wp-admin/includes/file.php\');
    require_once (ABSPATH . \'/wp-admin/includes/image.php\');
    global $wpdb;
    if (isset($_POST[\'submit\'])) {
        // Upload Exhibitor Logo
        $file = $_FILES[\'uploaded_doc\'];
        if (!empty($file)) {
            $uploads = wp_upload_dir();
            // Create \'user_avatar\' directory if not exist
            $folderPath = ABSPATH . \'wp-content/uploads/Reports\';
            if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

                 $ext = end((explode(".", $_FILES[\'uploaded_doc\'][\'name\'])));            
                if( $ext== \'pdf\' || $ext== \'docx\' ){                    
                $ABSPATH_userAvatarFullImage = ABSPATH . \'wp-content/uploads/Reports/\' . time() . \'.\' . $ext;
                if (move_uploaded_file($_FILES[\'uploaded_doc\'][\'tmp_name\'], $ABSPATH_userAvatarFullImage)) {                        
                    $data = array(
                    \'title\' => $_POST[\'title\'],
                    \'arabic_title\' => $_POST[\'arabic_title\'],
                    \'principle_investigators\' => $_POST[\'principle_investigators\'],
                    \'co_investgators\' => $_POST[\'co_investgators\'],
                    \'coverage_area\' => $_POST[\'coverage_area\'],
                    \'publication_year\' => $_POST[\'publication_year\'],
                    \'types\' => $_POST[\'types\'],
                    \'uploaded_doc\' => $_FILES[\'uploaded_doc\'][\'name\'],
                    \'create_date\'=> date(\'Y-m-d H:i:s\') 

                    );          
        $table = $wpdb->prefix . "reports_publication";         
        $result = $wpdb->insert($table, $data);

                }
                echo "1";
                }else{
                    echo "File not in format";
                }

        }


}
}
}

结束

相关推荐

如何在短码中调用javascript函数(JQuery)?

在这里提问之前,我已经搜索了一段时间,找到了一个关于使用快捷码和javascript调用创建wordpress插件的教程。但我无法让它在我这边起作用。本教程为here基本上,它应该添加一个显示预定义字符串的电传终端。我能够跟踪到绘制终端的部分。但我看不到代码中的什么地方,我们调用javascript函数来制作“动画”。有一个zip可以下载所有源代码,可以找到teletype javasources(未最小化)here所以,我的问题是,我不知道如何从php文件调用javascript/jquery函数。有没