400错误请求管理-AJAX文件上载

时间:2020-01-06 作者:sialfa

我在制作上传插件时遇到了一些问题。我正在使用ajax进行上传,但在第一次测试中,我遇到了400个错误请求。有解决方法吗?

这是js代码

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

    $(\'#process-upload\').on(\'click\', function(e){
      e.preventDefault();
      var data = new FormData();
      data.append(\'file\', $(\'#imageFile\').prop(\'files\')[0] );
      data.append(\'action\', \'new_message\');
      data.append(\'message\', $(\'#imageMessage\').val());

      $.ajax({
        url: wpu.ajaxurl,
        type: \'POST\',
        contentType: false,
        processData: false,
        data: data,
        success: function(response){
          console.log(response);
          window.alert(\'Done!\');
        }
      });

    });

  });
}(jQuery));
这是php:

public function __construct()
  {
    add_shortcode( \'upload-form\', array($this, \'upload_form\') );
    add_action( \'wp_enqueue_scripts\', array($this, \'main\') );
    add_action( \'admin_ajax_new_message\', array($this, \'process_upload\') );
    add_action( \'admin_ajax_nopriv_new_message\', array($this, \'process_upload\') );
  }

  public function main()
  {
    wp_enqueue_script( \'ajax-upload\', plugins_url( \'ajax-upload.min.js\' , __FILE__), array(\'jquery\'), null );
    wp_localize_script( \'ajax-upload\', \'wpu\', array(
        \'ajaxurl\' => admin_url(\'admin-ajax.php\')
      )
    );

  }

  public function upload_form( $attr, $content = null )
  {
    ob_start();
    ?>
      <form method="POST" enctype="multipart/form-data">
        <div class="custom-file">
          <input type="file" class="custom-file-input" id="imageFile" accept="image/*">
          <label class="custom-file-label" for="imageFile">Choose file</label>
        </div>
        <textarea class="form-control" id="imageMessage" name="message"></textarea>
        <button type="button" class="btn btn-outline-secondary" id="process-upload"><?php _e(\'Save\'); ?></button>
        <button type="reset" class="btn btn-outline-danger" id="cancel-upload"><?php _e(\'Cancel\'); ?></button>
      </form>
    <?php
    return ob_get_clean();
  }

  public function process_upload()
  {
    $file = array(
      \'name\' => $_FILES[\'imageFile\'][\'name\'],
      \'type\' => $_FILES[\'imagefile\'][\'type\'],
      \'tmp_name\' => $_FILES[\'imageFile\'][\'tmp_name\'],
      \'size\' => $_FILES[\'imageFile\'][\'size\'],
      \'error\' => $_FILES[\'imageFile\'][\'error\'],
    );

    $upload = wp_handle_upload( $file , array( \'test_form\' => false ) );

    var_dump($upload);

  }

1 个回复
最合适的回答,由SO网友:Chetan Vaghela 整理而成

你的行动应该是wp_ajaxwp_ajax_nopriv 而不是admin_ajax.

 add_action( \'wp_ajax_new_message\', array($this, \'process_upload\') );
 add_action( \'wp_ajax_nopriv_new_message\',array($this, \'process_upload\') );