在 Wordpress 中使用 AJAX 表单上传文件错误 - 指定文件上传测试失败

Posted

技术标签:

【中文标题】在 Wordpress 中使用 AJAX 表单上传文件错误 - 指定文件上传测试失败【英文标题】:Upload File Error with AJAX Form in Wordpress - Specified file failed upload test 【发布时间】:2021-01-22 15:09:53 【问题描述】:

我在同样的问题上卡住了几天,我希望有人可以帮助解决这个问题。我尝试了在 *** 上找到的多个函数,但似乎我做错了什么!

我需要使用 AJAX 将文件上传到 wordpress 库并在前端提交表单。

这是表格:

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' );

AJAX 调用:

jQuery(document).ready(function($)

    //$('#process-upload').on('click', function(e)
    $("#form-upload").on('submit',function(e)
        e.preventDefault();
        var el_form = $('#form-upload')

        //var data = new FormData();
        //data.append('action', 'new_upload_file');
        //data.append('imageFile', $('input[type=file]')[0].files[0] );
        //data.append('message', $('#imageMessage').val() );

        // If form is valid run function
        new_upload_file()

        // Ajax request.
        function new_upload_file() 

            $.ajax(
            url: localized_new_upload_file.admin_ajax_url,
            type: 'POST',
            //contentType: false,
            enctype: 'multipart/form-data',
            //processData: false,
            //data: data,
            dataType: 'json',
            data: 
                action: 'new_upload_file', // Set action without prefix 'wp_ajax_'.
                form_data: el_form.serialize()
            ,
            cache: false,
            success: function(response)
                console.log(response);
                window.alert('Done!');
            
            );
        
  
    );

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

我没有得到imagefile 字段的数据。这就是为什么我猜我收到错误Specified file failed upload test.

我的功能有什么问题.. 顺便说一下,我尝试了 $_FILES / $_POST 但我缺少一些东西。

编辑 JS文件

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>

PHP

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' );


【问题讨论】:

【参考方案1】:

在 $.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 中

$_FILES['imagefile'] 将授予您对文件的访问权限$_POST['message'] 将授予您对 textarea 文本的访问权限$_POST['_nonce'] 将授予您对 nonce 的访问权限$_POST['action'] 将授予您访问权限到行动

【讨论】:

还有一个问题,我怎样才能得到他上传文件的url?从响应中? wp_handle_upload 的返回值应该为您提供一个包含文件 url 的数组 是的,现在知道了。喜欢$movefile['url']。非常感谢

以上是关于在 Wordpress 中使用 AJAX 表单上传文件错误 - 指定文件上传测试失败的主要内容,如果未能解决你的问题,请参考以下文章

Wordpress 和 AJAX - 上传特色图片

如何在 wordpress 中通过 jQuery/Ajax 上传图片

Wordpress 是不是在劫持我的 Ajax 表单帖子?

在 Wordpress 中使用 ajax 提交表单

Wordpress 和 Ajax 表单提交

通过 AJAX 更新 wordpress 表单第二次不起作用