Laravel 中的文件系统与上传文件与磁盘
Filesystem vs UploadedFile vs Disk in Laravel
我目前正在使用 Laravel 进行项目工作,我真的不知道如何正确处理上传的文件。
我需要的是将上传的文件存储到特定目录(私有,只能由服务器访问),它是一个CSV文件,我需要处理它的数据。所以,我打算使用 fgetcsv 方法逐行读取文件,但是,我需要一个文件句柄。
根据文档,上传的文件存储在临时目录中,您可以通过调用请求对象的 file('variablename')
方法来检索表示文件的 UploadedFile
对象。由于我需要保留这些文件,因此我需要在 documentation 状态下调用存储方法(或者可能使用不同的方法)。可悲的是,存储方法returns相对于"disk root"的路径,这里指的是Disk
对象配置在FileSystem
对象中。可能对该路径使用 fopen
是行不通的,我需要一个绝对路径。
我想出的一个肮脏的解决方法是使用 storage_path 方法,因为我知道本地磁盘上配置的根是什么 (storage_path('app')
)。
会是这样的
$local_path = $file->store('uploads', 'local');
$abspath = storage_path('app') . '/' . $local_path;
// Pass the absolute path to the business layer
// In the business layer...
$fh = fopen($abspath, 'r');
// Do the thing
有没有更好的方法?
我终于找到了如何获取绝对路径的方法,但是该方法没有正式记录,但这对我有用:
$abspath = Storage::disk('local')->getDriver()->getAdapter()->applyPathPrefix($local_path);
我目前正在使用 Laravel 进行项目工作,我真的不知道如何正确处理上传的文件。
我需要的是将上传的文件存储到特定目录(私有,只能由服务器访问),它是一个CSV文件,我需要处理它的数据。所以,我打算使用 fgetcsv 方法逐行读取文件,但是,我需要一个文件句柄。
根据文档,上传的文件存储在临时目录中,您可以通过调用请求对象的 file('variablename')
方法来检索表示文件的 UploadedFile
对象。由于我需要保留这些文件,因此我需要在 documentation 状态下调用存储方法(或者可能使用不同的方法)。可悲的是,存储方法returns相对于"disk root"的路径,这里指的是Disk
对象配置在FileSystem
对象中。可能对该路径使用 fopen
是行不通的,我需要一个绝对路径。
我想出的一个肮脏的解决方法是使用 storage_path 方法,因为我知道本地磁盘上配置的根是什么 (storage_path('app')
)。
会是这样的
$local_path = $file->store('uploads', 'local');
$abspath = storage_path('app') . '/' . $local_path;
// Pass the absolute path to the business layer
// In the business layer...
$fh = fopen($abspath, 'r');
// Do the thing
有没有更好的方法?
我终于找到了如何获取绝对路径的方法,但是该方法没有正式记录,但这对我有用:
$abspath = Storage::disk('local')->getDriver()->getAdapter()->applyPathPrefix($local_path);