我目前工作的一个Laravel 5.5的项目,在这里我想对上传文件,而那时,我希望得到他们的网址后面的文件(我有使用它的客户端)。
现在我的代码看起来像这样:
public function pdfUploader(Request $request)
{
Log::debug('pdfUploader is called. ' . $request);
if ($request->hasFile('file') && $request->file('file')->isValid()) {
$extension = $request->file->extension();
$fileName = 'tmp' . round(microtime(true) * 1000) . '.' . $extension;
$path = $request->file->storeAs('temp', $fileName);
return ['status' => 'OK', 'path' => URL::asset($path)];
}
return ['status' => 'NOT_SAVED'];
}
它工作正常,我返回了OK状态和路径,但是当我要使用路径时,我得到了HTTP 404。我检查了一下,文件上传正常了。
我的想法是,我应该在路线中注册新的网址。如果必须的话,我该如何动态地执行它,如果没有必要,我的功能有什么问题?
事先找出答案。
默认情况下,laravel将所有上传的文件存储到存储目录中,例如,如果您调用$request->file->storeAs('temp', 'file.txt');
laravel将在其中创建temp
文件夹storage/app/
并将文件放置在其中:
$request->file->storeAs('temp', 'file.txt'); => storage/app/temp/file.txt
$request->file->storeAs('public', 'file.txt'); => storage/app/public/file.txt
但是,如果要使上传的文件可从Web访问,可以通过以下两种方法进行:
将您上传的文件移到公共目录
$request->file->move(public_path('temp'), $fileName); // => public/temp/file.txt
URL::asset('temp/'.$fileName); // http://example.com/temp/file.txt
注意:确保您的Web服务器具有写入公共目录的权限
创建从存储目录到公共目录的符号链接
php artisan storage:link
此命令将创建一个从public/storage
到的符号链接storage/app/public
,在这种情况下,我们可以将文件存储到文件中,storage/app/public
并通过符号链接从网络上访问它们:
$request->file->storeAs('public', $fileName); // => storage/app/public/file.txt
URL::asset('storage/'.$fileName); // => http://example.com/stoage/file.txt
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句