【问题标题】:How to upload a files in WordPress custom page template?如何在 WordPress 自定义页面模板中上传文件?
【发布时间】:2016-05-16 06:27:27
【问题描述】:

我有一个自定义页面模板。此模板有一个自定义表单,用户可以上传文件。现在,上传的文件不会上传到 MySQL,而是上传到文件系统/本地文件夹(本地计算机)。

我已经有一个 PHP sn-p,但是代码不工作我得到一个错误。

如何解决这个问题?

片段:

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

【问题讨论】:

    标签: php wordpress file-upload custom-wordpress-pages


    【解决方案1】:

    尝试以下sn-p,将文件上传到默认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
    }
    

    【讨论】:

    • 文件将保存到什么位置?我需要将文件保存在文件系统/本地计算机中
    • 文件将上传到/wp-content/uploads/目录,是的,这将是您的本地PC(如果wordpress在您的本地机器上)或您的服务器(您在云上的托管机器)
    • 不,保持原样。
    • 文件没有保存
    • 您的uploads 目录是否有适当的权限?您可以通过转到wp-admin/media/Add New 并尝试上传文件来检查文件夹权限。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2016-11-07
    • 2018-01-21
    相关资源
    最近更新 更多