Laravel,获取上传文件的URL [英] Laravel, getting uploaded file's url

查看:1427
本文介绍了Laravel,获取上传文件的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在Laravel 5.5项目中,我想想要 上传文件然后,然后我要获取文件的网址(我必须在客户端使用它).

I'm currently working on a Laravel 5.5 project, where I want to upload files, and then, I want to get their url back of the file (I have to use it client side).

现在我的代码如下:

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 .我检查了一下,文件上传正常了.

It works fine, I got back the OK status, and the path, but when I want to use the path, I got HTTP 404. I checked, the file is uploaded fine..

我的想法是,我应该在路线中注册新的网址.如果必须的话,我该如何动态地执行它,如果不必要的话,我的功能出了什么问题?

My thought is, I should register the new url in the routes. If I have to, how can I do it dynamically, and if its not necessary what is wrong with my function?

提前回答答案.

推荐答案

默认情况下,laravel将所有上传的文件存储到存储目录中,例如,如果您调用$request->file->storeAs('temp', 'file.txt');,laravel将在storage/app/中创建temp文件夹并将您的在那里保存文件:

By default laravel store all uploaded files into storage directory, for example if you call $request->file->storeAs('temp', 'file.txt'); laravel will create temp folder in storage/app/ and put your file there:

$request->file->storeAs('temp', 'file.txt'); => storage/app/temp/file.txt
$request->file->storeAs('public', 'file.txt'); => storage/app/public/file.txt

但是,如果您想使上传的文件可以从网络上访问,可以通过以下两种方法进行:

However, if you want to make your uploaded files accessible from the web, there are 2 ways to do that:

将您上传的文件移动到公共目录

$request->file->move(public_path('temp'), $fileName); // => public/temp/file.txt
URL::asset('temp/'.$fileName); // http://example.com/temp/file.txt

注意:确保您的Web服务器具有写入公用目录的权限

NOTE: make sure that your web server has permissions to write to the public directory

创建从存储目录到公共目录的符号链接

php artisan storage:link

此命令将创建一个从public/storagestorage/app/public的符号链接,在这种情况下,我们可以将文件存储到storage/app/public中,并通过符号链接从网络上访问它们:

This command will create a symbolic link from public/storage to storage/app/public, in this case we can store our files into storage/app/public and make them accessible from the web via symlinks:

$request->file->storeAs('public', $fileName); // => storage/app/public/file.txt
URL::asset('storage/'.$fileName); // => http://example.com/stoage/file.txt

这篇关于Laravel,获取上传文件的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆