在 Laravel 的控制器中处理文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40033879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling File Upload in Laravel's Controller
提问by Emz
How can I use the following PHP $_FILES using Laravel's Request object? (i'm using Laravel 5.3)
如何使用 Laravel 的 Request 对象使用以下 PHP $_FILES?(我正在使用 Laravel 5.3)
$_FILES["FileInput"]
$_FILES["FileInput"]["size"]
$_FILES['FileInput']['type']
$_FILES['FileInput']['name']
$_FILES['FileInput']['tmp_name']
Anyone has an idea working this before that would be very much appreciated. Thank you!
任何人在此之前有一个想法,将不胜感激。谢谢!
回答by iCoders
Retrieving Uploaded Files
检索上传的文件
You may access uploaded files from a Illuminate\Http\Request instance using the file method or using dynamic properties. The file method returns an instance of the Illuminate\Http\UploadedFile class, which extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file:
您可以使用 file 方法或使用动态属性从 Illuminate\Http\Request 实例访问上传的文件。file 方法返回 Illuminate\Http\UploadedFile 类的实例,该类扩展了 PHP SplFileInfo 类并提供了多种与文件交互的方法:
$file = $request->file('photo');
$file = $request->photo;
You may determine if a file is present on the request using the hasFile method:
您可以使用 hasFile 方法确定请求中是否存在文件:
if ($request->hasFile('photo')) {
//
}
Validating Successful Uploads
验证成功上传
In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method:
除了检查文件是否存在之外,您还可以验证通过 isValid 方法上传文件没有问题:
if ($request->file('photo')->isValid()) {
//
}
File Paths & Extensions
文件路径和扩展名
The UploadedFile class also contains methods for accessing the file's fully-qualified path and its extension. The extension method will attempt to guess the file's extension based on its contents. This extension may be different from the extension that was supplied by the client:
UploadedFile 类还包含用于访问文件的完全限定路径及其扩展名的方法。extension 方法将尝试根据文件的内容猜测文件的扩展名。此扩展可能与客户端提供的扩展不同:
$path = $request->photo->path();
$extension = $request->photo->extension();
To get File name
获取文件名
$filename= $request->photo->getClientOriginalName();
Ref:https://laravel.com/docs/5.3/requests
参考:https: //laravel.com/docs/5.3/requests
Example
例子
$file = $request->file('photo');
//File Name
$file->getClientOriginalName();
//Display File Extension
$file->getClientOriginalExtension();
//Display File Real Path
$file->getRealPath();
//Display File Size
$file->getSize();
//Display File Mime Type
$file->getMimeType();
//Move Uploaded File
$destinationPath = 'uploads';
$file->move($destinationPath,$file->getClientOriginalName());