【问题标题】:Getting error "Specified file failed upload test" when adding file from Base64 decode从 Base64 解码添加文件时出现错误“指定文件上传测试失败”
【发布时间】:2020-12-30 18:12:18
【问题描述】:

我在网上到处搜索,找不到解决办法。

我正在尝试使用wp_handle_upload(),但只有当我尝试上传从base64_decode() 创建的文件时,我才会收到“指定文件上传测试失败”;

我很确定这不是权限或服务器问题。这里还有一些注意事项:

  • 将 WordPress 上的文件上传到媒体库时一切正常
  • 当我直接从$_FILES 获取文件时,我的代码甚至可以正常工作。当我开始创建自己的 $file 数组时,它停止工作。
  • 我在完全不同的服务器上有另一个实时版本,问题是一样的
  • 我尝试过'image/png''image/jpg' 的文件类型。
  • 我使用 tmp_name 的上传目录,但这并没有什么不同
  • 临时文件正在成功上传

更多信息:我将print_r( is_uploaded_file( $file['tmp_name'] ));die; 行添加到/wp-admin/includes/file.php 中的第822 行。我相信这是因为这是错误的返回错误。

    $upload_dir       = wp_upload_dir();
    $upload_path      = get_stylesheet_directory().'/tmp-images/';
    $img = $_POST['main_image_0'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $decoded          = base64_decode($img) ;
    $filename         = $_POST['file_name'];
    $hashed_filename  = md5( $filename . microtime() ) . '_' . $filename;

    // @new
    if (!is_dir($upload_path)) {
        // dir doesn't exist, make it
        mkdir('upload/promotions/' . $month);
    }
    
    $image_upload     = file_put_contents( $upload_path . $hashed_filename, $decoded );

    //HANDLE UPLOADED FILE
    if( !function_exists( 'wp_handle_sideload' ) ) {
      require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    // Without that I'm getting a debug error!?
    if( !function_exists( 'wp_get_current_user' ) ) {
      require_once( ABSPATH . 'wp-includes/pluggable.php' );
    }

    // @new
    $file             = array();
    $file['error']    = 0;
    $file['tmp_name'] = $upload_path . $hashed_filename;
    $file['name']     = $filename;
    $file['type']     = 'image/jpeg';
    $file['size']     = filesize( $upload_path . $hashed_filename );        
    
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );

    $file_return = wp_handle_upload( $file, array('test_form' => false ) );
    print_r($file);print_r($file_return);die;

返回

Array
(
    [error] => 0
    [tmp_name] => /var/www/example/wp-content/themes/mytheme/tmp-images/eea84bdc7b9b79a10898425c79f62fc2_20130202_173509.jpg
    [name] => 20130202_173509.jpg
    [type] => image/jpeg
    [size] => 273444
)
Array
(
    [error] => Specified file failed upload test.
)

【问题讨论】:

    标签: php wordpress file-upload


    【解决方案1】:

    我找到了原因。这是由于使用is_uploaded_filewhich is specifically designed to handle HTTP POST requests 的功能。所以一切都在按应有的方式进行。我只是没有意识到wp_handle_upload() 只是为了这个目的。我在调用函数之前使用了 base64 并对其进行了转换,这意味着它不再处理来自发布请求的文件。

    为了解决我的问题,我改用wp_upload_bits (ref)。

    【讨论】:

      猜你喜欢
      • 2019-10-10
      • 2021-01-22
      • 2016-08-02
      • 1970-01-01
      • 2019-08-09
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多