【发布时间】: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