如何通过wordpress中的jQuery / Ajax上传图像

时间:2017-06-15 08:15:20

标签: php jquery ajax wordpress image-uploading

我正在尝试从wordpress注册表单(自定义表单)上传图像。我找到了许多通过ajax上传的方法,但没有一种方法可以帮助我。

这里是没有标签的表格

<div class="lofin-form"><div class="row">                       
<input type="text" name="first_name" id="first_name" placeholder="First Name" class="input" value="" size="20" />
</div>
<div class="row"> 
<lable>Id proof <input type="file" name="id_proof"  id="id_proof" class="input" />
</div>
<p class="submit"><input type="submit" name="wp-submit" id="wp-submit-register" class="btn vernil small" value="'.__('Sign Up','wpestate').'" /></p>
</div>

这是jQuery脚本代码

$('#wp-submit-register').click(function(){
  wpestate_register();
});

function wpestate_register (){
var  user_role =  $('#first_name').val();
var fdata = new FormData();
fdata.append('file', $('#id_proof')[0].files[0]);
$.ajax({
    type: 'POST', 
    url: ajaxurl,
    data: {
        'action' :   'ajax_free_register_form',
        'first_name'  :   first_name,
        'file_data'   : fdata

    },
    success:function(data) {
        alert('success');
    }
}

这是php函数

add_action( 'wp_ajax_nopriv_ajax_free_register_form', 'ajax_free_register_form' );  
add_action( 'wp_ajax_ajax_free_register_form', 'ajax_free_register_form' );  

function ajax_free_register_form(){
   $first_name  =   trim( $_POST['first_name'] ) ;
   $id_proof   =   $_FILES['id_proof'] ; 
}

解决[编辑]

只需在表单中添加表单标记并提供ID“user_reg_form”即可。

<form id="user_reg_form" action="" method="post" enctype="multipart/form-data">
----------------------input fields goes here-------------------
</form>

并更新脚本:

$('#wp-submit-register').click(function(){
   wpestate_register();
});

function wpestate_register (){
var formdata = new FormData( $("#user_reg_form")[0] );
formdata.append('action', 'ajax_free_register_form');
$.ajax({
   type: 'POST', 
   cache: false,
   contentType: false,
   processData: false,
   url: ajaxurl,
   data: formdata,
   success:function(data) {
      alert('success');
   }
});
}

之后,您只需使用

获取上传的文件即可
$attachment = $_FILES['id_proof'];

3 个答案:

答案 0 :(得分:1)

确保您的ajax版本支持它。您需要将ajax processData和contentType设置为FALSE。 Para contentType表示不设置Content-Type HEAD,而processData表示不将数据处理成字符串。

试试这个:

$.ajax({
    type: 'POST', 
    url: ajaxurl,
    data: fdata,
    processData : false,
    contentType: false,
    success:function(data) {
        alert('success');
    }
}

答案 1 :(得分:1)

通过wordpress中的jQuery / Ajax上传图片

HTML:

    <input type="file" id="ct-file" name="ct_file">

JS:

    var sofg_mixup = jQuery.noConflict();
    sofg_mixup(document).ready(function() {
        sofg_mixup('#ct-file').change(function() {
            var fileInput = sofg_mixup('#ct-file').prop('files')[0];
            var myFormData = new FormData();
            myFormData.append('ct_file', fileInput);
            sofg_mixup.ajax({
                url: '<?php echo get_template_directory_uri() ?>/save_file.php',
                type: 'POST',
                processData: false, // important
                contentType: false, // important
                dataType: 'json',
                data: myFormData,
                success: function(jsonData) {
                    console.log(jsonData.url);
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    console.log(xhr);
                }
            });
        });
    });

PHP

require_once('../../../../../wp-load.php');
if (isset($_FILES['ct_file'] ) && !empty($_FILES['ct_file']['name']) )
        {
            $allowedExts = array("doc", "docx", "pdf");
            $temp = explode(".", $_FILES["ct_file"]["name"]);
            $extension = end($temp);
            if ( in_array($extension, $allowedExts))
            {
                if ( ($_FILES["ct_file"]["error"] > 0) && ($_FILES['ct_file']['size'] <= 3145728 ))
                {
                    $response = array(
                        "status" => 'error',
                        "message" => 'ERROR Return Code: '. $_FILES["ct_file"]["error"],
                        );
                }
                else
                {
                    $uploadedfile = $_FILES['ct_file'];
                    $upload_name = $_FILES['ct_file']['name'];
                    $uploads = wp_upload_dir();
                    $filepath = $uploads['path']."/$upload_name";

                    if ( ! function_exists( 'wp_handle_upload' ) )
                    {
                        require_once( ABSPATH . 'wp-admin/includes/file.php' );
                    }
                    require_once( ABSPATH . 'wp-admin/includes/image.php' );
                    $upload_overrides = array( 'test_form' => false );
                    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
                    if ( $movefile && !isset( $movefile['error'] )  ) {

                        $file = $movefile['file'];
                        $url = $movefile['url'];
                        $type = $movefile['type'];

                        $attachment = array(
                            'post_mime_type' => $type ,
                            'post_title' => $upload_name,
                            'post_content' => 'File '.$upload_name,
                            'post_status' => 'inherit'
                            );

                        $attach_id=wp_insert_attachment( $attachment, $file, 0);
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );

                    }

                    $response = array(
                        "status" => 'success',
                        "url" => $url
                        );

                }
            }
            else
            {
                $response = array(
                    "status" => 'error',
                    "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
                    );
            }
        }
        print json_encode($response);
        exit;

答案 2 :(得分:0)

使用ajaxForm()jquery插件。它会像魅力一样对你有用。参考http://malsup.com/jquery/form/#getting-started

请参阅此https://forum.jquery.com/topic/using-ajaxsubmit-function-extra-parameter