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

时间:2022-08-28 08:04:44

I am trying to upload image from wordpress register form(custom form). I found many ways to upload via ajax but none of them working for me.

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

here is form without tag

这是没有标签的表格

<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>

and here is the jQuery script code

这是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');
    }
}

And here is php function

这是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'] ; 
}

RESOLVE [EDIT]

Just add form tag in form and gave an ID 'user_reg_form'.

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

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

And update the script:

并更新脚本:

$('#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');
   }
});
}

After that you can simply get the uploaded file with

之后,您可以简单地获取上传的文件

$attachment = $_FILES['id_proof'];

3 个解决方案

#1


1  

Make sure your version of ajax support it.And you need to set ajax processData and contentType to FALSE. Para contentType means do not set the Content-Type HEAD,and processData means do not handle the data into string.

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

Try this:

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

#2


1  

upload image through jQuery/Ajax in wordpress

通过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;

#3


0  

use ajaxForm() jquery plugin. It will work for you like a charm. Reference http://malsup.com/jquery/form/#getting-started

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

Refer this https://forum.jquery.com/topic/using-ajaxsubmit-function-extra-parameter too

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

#1


1  

Make sure your version of ajax support it.And you need to set ajax processData and contentType to FALSE. Para contentType means do not set the Content-Type HEAD,and processData means do not handle the data into string.

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

Try this:

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

#2


1  

upload image through jQuery/Ajax in wordpress

通过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;

#3


0  

use ajaxForm() jquery plugin. It will work for you like a charm. Reference http://malsup.com/jquery/form/#getting-started

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

Refer this https://forum.jquery.com/topic/using-ajaxsubmit-function-extra-parameter too

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