我在网上到处搜索,找不到解决方案。
我正在尝试使用wp_handle_upload()
但只有当我尝试上传从base64_decode()
创建的文件时,我才收到"指定文件上传测试失败";
我很确定这不是权限或服务器问题。以下是更多注意事项:
- 将WordPress上的文件上传到媒体库时一切正常
- 当我直接从
$_FILES
获取文件时,我的代码甚至有效。当我开始必须创建自己的$file
数组时,它停止工作。 - 我在完全不同的服务器上有另一个实时版本,问题是相同的
- 我已经尝试了
'image/png'
和'image/jpg'
文件类型。 - 我正在使用上传目录进行
tmp_name
但这并没有区别 - 临时文件已成功上传
更多信息:我在/wp-admin/include/file.php 中将第print_r( is_uploaded_file( $file['tmp_name'] ));die;
行添加到第 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.
)
我找到了原因。这是由于使用专门设计用于处理HTTP POST请求的is_uploaded_file
函数。所以一切都按照它应该的方式进行。我只是没有意识到wp_handle_upload()
只是为了这个目的。 我在调用函数之前使用了 base64 并对其进行了转换,这意味着它不再处理来自 post 请求的文件。
为了解决我的问题,我改用了wp_upload_bits
(参考)。