我有自定义页面模板。此模板具有用户可以上载文件的自定义表单。现在,上传的文件不会在MySQL中上传,而是在文件系统/本地文件夹(本地计算机)中上传。
我已经有了一个PHP代码段,但代码无效,我收到了错误。
如何解决这个问题?
段:
if(isset($_POST['submit'])){
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$resumeFile = isset($_FILE['resumeFile']['name']) ? $_FILE['resumeFile']['name']: '';
$info = pathinfo($_FILES['resumeFile']['name']);
$ext = $info['extension'];
$file_rename= $lastName.$ext;
$target = 'C://xampp/htdocs/files/'.$file_rename;
move_uploaded_file($_FILES['resumeFile']['tmp_name'], $target);
}
错误:
Notice: Undefined index: resumeFile .... on line 130
Notice: Undefined index: extension .... on line 131
Notice: Undefined index: resumeFile .... on line 135
答案 0 :(得分:1)
请尝试使用以下代码段,将文件上传到默认uploads
目录以外的其他目录。
function change_my_upload_directory( $dir ) {
return array (
'path' => WP_CONTENT_DIR . '/your-custom-dir',
'url' => $dir['baseurl'] . '/wp-content/your-custom-dir',
'subdir' => '/your-custom-dir',
) + $dir;
}
if( isset( $_FILES[ "resumeFile" ] ) ) {
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
// Overrides the uploads directory location
add_filter( 'upload_dir', 'change_my_upload_directory' );
$movefile = wp_handle_upload( $_FILES[ "resumeFile" ], array( 'test_form' => false ) );
// Remove the filter, so that subsequant uploads will be dsent to default uploads directory
remove_filter( 'upload_dir', 'change_my_upload_directory' );
return $movefile;
}
return false;
wp_handle_upload
将返回包含以下属性的对象
$movefile[ 'file' ] // uploaded file object
$movefile[ 'url' ] // current url ( file location ) of the file
$movefile[ 'type' ] // uploaded file type
如果wp_handle_upload
失败,它将返回错误对象,您可以像这样检查上传失败
if( isset( $movefile[ 'error' ] ) ) {
// handle the error
}