且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Laravel的控制器中处理文件上传

更新时间:2023-09-20 07:53:58

检索上传的文件

您可以使用文件方法或动态属性从Illuminate \ Http \ Request实例访问上载的文件.file方法返回Illuminate \ Http \ UploadedFile类的实例,该实例扩展了PHP SplFileInfo类并提供了多种与文件交互的方法:

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;

您可以使用hasFile方法确定请求中是否存在文件:

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

if ($request->hasFile('photo')) {
    //
}

验证上传成功

除了检查文件是否存在之外,您还可以验证通过isValid方法上传文件没有问题:

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()) {
    //
}

文件路径和扩展程序

UploadedFile类还包含用于访问文件的标准路径及其扩展名的方法.扩展名方法将尝试根据其内容猜测文件的扩展名.此扩展名可能与客户端提供的扩展名不同:

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

获取文件名

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

参考: https://laravel.com/docs/5.3/requests

示例

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