【问题标题】:Laravel: how to access a file in the local disk? - File does not existLaravel:如何访问本地磁盘中的文件? - 文件不存在
【发布时间】:2017-09-02 14:49:42
【问题描述】:

我正在尝试在 laravel 中上传 Excel 文件后对其进行编辑。 该文件已上传到本地磁盘,因此任何人都无法从公众访问它。

文件系统.php

'local' => [
        'driver' => 'local',
        'root' => storage_path('app')

Routes.php

Route::get('test',function()
{

    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel = PHPExcel_IOFactory::load(Storage::disk('local')->url('margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'));
    $objPHPExcel->setActiveSheetIndex(0);
    echo $objPHPExcel->getActiveSheet()->getHighestRow();
})->middleware('admin');

我不断收到错误:

Could not open /storage/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx for reading! File does not exist.

这行得通

     $objPHPExcel = PHPExcel_IOFactory::load('..'.Storage::disk('local')->url('app/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'));

但这很烦人。我认为在 filesystems.php 中指定 'root' => storage_path('app') 意味着 Storage::disk('local') 将直接在应用程序中

【问题讨论】:

  • 您的 0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx 文件在正确的路径中吗?
  • 您将文件传递给 storage/app 但尝试从 storage/margin 获取它尝试在您的 url 函数中添加 app/
  • 还是同样的错误。但这有效。 “……” Storage::disk('local')->url('app/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx')。但这很烦人。我认为在 filesystems.php 中指定 'root' => storage_path('app') 意味着 Storage::disk('local') 将直接在应用程序中

标签: php laravel xampp composer-php phpexcel


【解决方案1】:

URL method 用于获取文件的 URL(即:从浏览器访问它的东西)。你想用get()方法的id。

$contents = Storage::get(''margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'');

话虽如此,使用 Laravel 操作上传的文件仍有更简单的方法。

// this will take the uploaded file from the request
// and store it into `/storage/someFolder`
$path = $request->file('file')->store('someFolder');

然后您可以使用返回给$path 的值来访问该文件。

编辑

经过下面的讨论,OP决定,即使不是完美的解决方案,他也会使用$objPHPExcel = PHPExcel_IOFactory::load('..'.Storage::disk('local')->url($fileLocation));

【讨论】:

  • Storage::get 返回此错误:Excel2007.php 第 234 行中的 ErrorException:file_exists() 期望参数 1 是有效路径,给定字符串。我正在使用“存储”方式保存文件,但它返回此路径:“margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx”,我在我的代码中使用它但它不起作用。真烦人。
  • @medoampir 你能确认 `/storage/app/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx' 中确实有一个文件吗?
  • @maedoampir 你的问题表明你在哪里得到错误,你在哪里得到它,因为“url()”得到一个 URL,而不是文件的路径。使用带有正确路径的 'Sorage::get()' (无需在路径中指定 'app')似乎是正确的方法,如果仅仅是因为你认为代码看起来很丑;-)
  • 我只是期待在 filesystems.php 中定义这部分之后('local' => [ 'driver' => 'local', 'root' => storage_path('app'),) .为了能够使用这部分 (Storage::disk('local')) 作为 laravel 的指令来获取 app 文件夹中的文件。为什么我必须将这部分'..'放在 Storage::disk 之前? :(
  • 您刚刚说了两个 cmets,使用 Storage::get('margin/analyser/0IGkQ‌​QgmGXkHrV9ISnBTrGyZF‌​UPfjz3cWJbLGbDN.xlsx‌​') 有效。那里没有“..”?
猜你喜欢
  • 2023-03-13
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2021-12-05
  • 1970-01-01
  • 2011-02-07
相关资源
最近更新 更多