首页 > 解决方案 > 读取存储在媒体文件夹中的 excel 文件

问题描述

我正在开发一个 WordPress 插件,它需要上传一个 excel 文件,然后读取其中的数据。

我正在使用函数“media_handle_upload”来上传 excel 文件,然后,当我尝试使用 SpreadsheetReader 读取文件时,出现一个错误,指出该文件不可读。

这就是我正在编码的内容,(我知道这是可怕的编码,但我正在学习,这只是为了让插件正常工作)

if(isset($_FILES['test_upload_pdf'])){
        $pdf = $_FILES['test_upload_pdf'];

        // Use the wordpress function to upload
        // test_upload_pdf corresponds to the position in the $_FILES array
        // 0 means the content is not associated with any other posts
        $uploaded=media_handle_upload('test_upload_pdf', 0);
        // Error checking using WP functions
        if(is_wp_error($uploaded)){
                echo "Error uploading file: " . $uploaded->get_error_message();
        }else{
            echo $pdf."<br>";
            $year = date('Y');
            $month = date('m');
            $targetPath = get_site_url()."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
            $targetPath2 = $_SERVER['DOCUMENT_ROOT']."/".$_SERVER["HTTP_HOST"]."/wp-content/uploads/".$year."/".$month."/".$_FILES['test_upload_pdf']['name'];
            echo "<br>";

            echo $targetPath2;
            echo "<br>";
            try
            {
                $Reader = new SpreadsheetReader($targetPath2);
            }
            catch (Exception $E)
            {
                echo $E -> getMessage();
            }

我认为阅读器不起作用,因为试图访问“localhost”而不是物理文件夹,例如,其中一个 $targetPath 打印:

http://127.0.0.1/wordpress/wp-content/uploads/2019/04/example.xlsx

所以...我的问题是,有一种方法可以访问媒体文件,以便我可以用阅读器打开它们?

谢谢。

标签: phpwordpresswordpress-plugin-creation

解决方案


也许这有帮助:

https://developer.wordpress.org/reference/functions/wp_upload_dir/

否则尝试硬编码文件夹“/your/path/to/upload/folder/file.extension”并了解如何以编程方式创建它


推荐阅读