Php Wordpress中AJAX表单的上载文件错误-指定的文件上载测试失败

Php Wordpress中AJAX表单的上载文件错误-指定的文件上载测试失败,php,jquery,ajax,wordpress,file-upload,Php,Jquery,Ajax,Wordpress,File Upload,我在同样的问题上被困了几天,我希望有人能帮我解决这个问题。我尝试了stackoverflow上的多种功能,但似乎我做了一些完全错误的事情 我需要上传一个文件到wordpress库,在前端使用AJAX提交表单 表格如下: function shortcode__new_upload_file() { /** * @var WP_User $current_user */ $current_user = $GLOBALS['current_user'];

我在同样的问题上被困了几天,我希望有人能帮我解决这个问题。我尝试了stackoverflow上的多种功能,但似乎我做了一些完全错误的事情

我需要上传一个文件到wordpress库,在前端使用AJAX提交表单

表格如下:

function shortcode__new_upload_file() {
    /**
     * @var     WP_User $current_user
     */
    $current_user = $GLOBALS['current_user'];

    ob_start(); ?>

    <form id="form-upload" method="POST" enctype="multipart/form-data">
        <div class="custom-file">
            <input type="file" name="imagefile" class="custom-file-input" id="imageFile">

          <label class="custom-file-label" for="imageFile">Choose file</label>
        </div>
        <textarea class="form-control" id="imageMessage" name="message"></textarea>
        <button type="submit" class="btn btn-outline-secondary submit" id="process-upload"><?php _e('Save'); ?></button>
        <button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
     </form>


    <?php
    $html = ob_get_clean();

    return $html;
}
// Ads shortcode so you can use the form anywhere you want.
add_shortcode( 'new_upload_file', 'shortcode__new_upload_file' );
我没有获取imagefile字段的数据。这就是为什么我猜我得到了一个错误指定文件上传测试失败

我的功能有什么问题。。顺便说一下,我试过$\u FILES/$\u POST,但我缺少一些东西

编辑 JS文件

形式

PHP


在$.ajax中使用FormData对象时,直接将其作为数据字段传递

jQuery(document).ready(function($) {

    
    //$("#form-upload").submit(function(e){
    $("#form-upload").on('submit',function(e){
        e.preventDefault();
        
        var formData = new FormData( this );
        formData.append('action', 'new_upload_file');
        //formData.append('_nonce', $('input[name*="my_token"]') ).val();
        //formData.append('_nonce', $this.closest('form').find('.nonce').val();
        formData.append('_nonce', $(this).find('input[name*="my_token"]').val() );
        
        
        // Ajax request.
       
            $.ajax({
                url: localized_new_upload_file.admin_ajax_url,
                type: 'POST',
                data: formData,  //<----- Pass the formdata object only
                contentType: false,
                cache: false,
                processData: false,
                success: function(response){
                    console.log(response);
                    window.alert('Done!');
                }
            });

        return false;
    });
});
在PHP中

$\u文件['imagefile']将允许您访问该文件 $\u POST['message']将允许您访问文本区域文本 $\u POST[''u nonce']将允许您访问nonce
$\u POST['action']将为您提供访问该操作的权限

还有一个问题,我如何获取上传文件的url?从响应中?wp_handle_upload的返回值应该为您提供一个带有文件url的数组是的,现在就得到了。比如$movefile['url']。谢谢
function upload_file_callback(){

    
    // get entered form data
    parse_str( $_POST['form_data'], $form_data );

    $postarr = array();
    
    // merge all array and make new array, now get data for each input like following: $form_data[LUBUVNA_PREFIX.'from']
    $postarr = array_merge( $postarr, $form_data );

    
    if ( ! function_exists( 'wp_handle_upload' ) ) {
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    //$uploadedfile = isset($_FILES['imagefile']) ? $_FILES['imagefile'] : '';
    
    $uploadedfile = $form_data['imagefile']; //$_FILES['imagefile'];

    $upload_overrides = array( 'test_form' => false );

    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); 

    if ( $movefile && !isset( $movefile['error'] ) ) {
        $feedback = "File is valid, and was successfully uploaded.\n";
        var_dump( $movefile);
    } else {
        /**
         * Error generated by _wp_handle_upload()
         * @see _wp_handle_upload() in wp-admin/includes/file.php
         */
        $feedback = print_r($movefile, true);
    }
    
    
    // send email with details
    $headers = [
     'MIME-Version: 1.0',
     'From: myemailfrom@hotmail.com',
     'Content-Type: text/html; charset=UTF-8'
    ];
    $headers = implode("\r\n", $headers);
    wp_mail('myemailto@gmail.com','Script Ran','<br>FEEDBACK:<br>'.$feedback. '<br>FORM Array:<br>' . print_r($postarr, true) ,$headers);
    
}

//add_action('wp_ajax_nopriv_new_upload_file', 'upload_file_callback');
add_action( 'wp_ajax_new_upload_file', 'upload_file_callback' );
FEEDBACK:
Array ( [error] => Specified file failed upload test. ) NASH TEXT: 
FORM Array:
:Array ( [message] => car ) 
jQuery(document).ready(function($) {

    
    //$("#form-upload").submit(function(e){
    $("#form-upload").on('submit',function(e){
        e.preventDefault();
        

        var $this = $(this);
        var formData = new FormData( $this[0] );
        formData.append('action', 'new_upload_file');
        //formData.append('_nonce', $('input[name*="my_token"]') ).val();
        //formData.append('_nonce', $this.closest('form').find('.nonce').val();
        formData.append('_nonce', $(this).find('input[name*="my_token"]').val() );
        
        
        // Ajax request.
       
            $.ajax({
            url: localized_new_upload_file.admin_ajax_url,
            type: 'POST',
            data: { 'form_data' :  formData },
            contentType: false,
            //enctype: 'multipart/form-data',
            cache: false,
            processData: false,
            success: function(response){
                    console.log(response);
                    window.alert('Done!');
                }
            });

        return false;
    });
});
    <form id="form-upload" method="POST" enctype="multipart/form-data">
        <div class="custom-file">
            <!--<input type="file" name="imagefile" class="custom-file-input" id="imageFile" accept="image/*">-->
            <input type="file" name="imagefile" class="custom-file-input" id="imageFile">

          <label class="custom-file-label" for="imageFile">Choose file</label>
          <!--<input name="my_token" class="nonce" value="<?php //echo wp_create_nonce("my_token"); ?>" type="hidden">-->
        <?php wp_nonce_field( SECURE_AUTH_SALT, 'my_token' ) ?>
        </div>
        <textarea class="form-control" id="imageMessage" name="message"></textarea>
        <button type="submit" class="btn btn-outline-secondary submit" id="process-upload"><?php _e('Save'); ?></button>
        <button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e('Cancel'); ?></button>
     </form>
function script__new_upload_file() {
    wp_enqueue_media();
    wp_enqueue_script(
        'new_upload_file',
        get_stylesheet_directory_uri(). '/ajax-file-upload.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
    
    wp_localize_script( 'new_upload_file', 'localized_new_upload_file', array( 
        'admin_ajax_url' => admin_url( 'admin-ajax.php' ),
        //'security'  => wp_create_nonce( 'my-special-string' )
    ));
}
// Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL.
add_action( 'wp_enqueue_scripts', 'script__new_upload_file' );



function upload_file_callback(){

        
    // get entered form data
    parse_str( $_POST['form_data'], $form_data );

    $postarr = array();
    
    // merge all array and make new array, now get data for each input like following: $form_data[LUBUVNA_PREFIX.'from']
    $postarr = array_merge( $postarr, $form_data );

    
    if ( ! function_exists( 'wp_handle_upload' ) ) {
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    //$uploadedfile = isset($_FILES['imagefile']) ? $_FILES['imagefile'] : '';

    $uploadedfile = $form_data['imagefile']; //$_FILES['imagefile'];
    //print_r($uploadedfile);
    // die();

    $upload_overrides = array( 'test_form' => false );

    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); 

    if ( $movefile && !isset( $movefile['error'] ) ) {
        $feedback = "File is valid, and was successfully uploaded.\n";
        var_dump( $movefile);
    } else {
        /**
         * Error generated by _wp_handle_upload()
         * @see _wp_handle_upload() in wp-admin/includes/file.php
         */
        $feedback = print_r($movefile, true);
    }
    
    
    
    // send email with details
    $headers = [
     'MIME-Version: 1.0',
     'From: myemailfrom@hotmail.com',
     'Content-Type: text/html; charset=UTF-8'
    ];
    $headers = implode("\r\n", $headers);
    wp_mail('myemailto@gmail.com','Script Ran','<br>FEEDBACK:<br>'.$feedback. '<br>FORM Array:<br>' . print_r($postarr, true) ,$headers);
    
}

add_action('wp_ajax_nopriv_new_upload_file', 'upload_file_callback');
add_action( 'wp_ajax_new_upload_file', 'upload_file_callback' );


jQuery(document).ready(function($) {

    
    //$("#form-upload").submit(function(e){
    $("#form-upload").on('submit',function(e){
        e.preventDefault();
        
        var formData = new FormData( this );
        formData.append('action', 'new_upload_file');
        //formData.append('_nonce', $('input[name*="my_token"]') ).val();
        //formData.append('_nonce', $this.closest('form').find('.nonce').val();
        formData.append('_nonce', $(this).find('input[name*="my_token"]').val() );
        
        
        // Ajax request.
       
            $.ajax({
                url: localized_new_upload_file.admin_ajax_url,
                type: 'POST',
                data: formData,  //<----- Pass the formdata object only
                contentType: false,
                cache: false,
                processData: false,
                success: function(response){
                    console.log(response);
                    window.alert('Done!');
                }
            });

        return false;
    });
});