在Laravel的控制器中处理文件上传 [英] Handling File Upload in Laravel's Controller

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

问题描述

如何通过Laravel的Request对象使用以下PHP $ _FILES?(我正在使用Laravel 5.3)

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!

推荐答案

检索上传的文件

您可以使用文件方法或动态属性从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());

这篇关于在Laravel的控制器中处理文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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