简体   繁体   English

在Laravel控制器中处理文件上载

[英]Handling File Upload in Laravel's Controller

How can I use the following PHP $_FILES using Laravel's Request object? 如何使用Laravel的Request对象使用以下PHP $ _FILES? (i'm using Laravel 5.3) (我正在使用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! 谢谢!

Retrieving Uploaded Files 检索上传的文件

You may access uploaded files from a Illuminate\\Http\\Request instance using the file method or using dynamic properties. 您可以使用文件方法或使用动态属性从Illuminate \\ Http \\ Request实例访问上载的文件。 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 \\ 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. UploadedFile类还包含用于访问文件的完全限定路径及其扩展名的方法。 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: 此扩展可能与客户端提供的扩展不同:

$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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM