简体   繁体   中英

Handling File Upload in Laravel's Controller

How can I use the following PHP $_FILES using Laravel's Request object? (i'm using 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. 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 = $request->file('photo');

$file = $request->photo;

You may determine if a file is present on the request using the hasFile method:

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:

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:

$path = $request->photo->path();

$extension = $request->photo->extension();

To get File name

$filename= $request->photo->getClientOriginalName();

Ref: 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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