1. 获取上传文件
Laravel 使用 Illuminate\Http\Request 的 file() 方法来获取用户上传的文件 ,返回 Symfony\Component\HttpFoundation\File\UploadedFile 实例
$request->file('photo');
// 或者
$request->photo;
2. 验证上传文件
验证上传文件要分两步 ,首先验证用户是否有上传文件 ,如果有再验证文件是否上传成功
if ($request->hasFile('file') && $request->file('file')->isValid()) {
// isValid() 在文件自身上调用 ,如果没有上传文件就调用会产生报错 , 因此先使用 hasFile() 检测是否有上传文件
}
3. Symfony\Component\HttpFoundation\File\UploadedFile 成员
// 继承关系
Symfony\Component\HttpFoundation\File\UploadedFile extends Symfony\Component\HttpFoundation\File\File;
下列方法名中带有 Client 的 ,表示相关信息是从请求中提取 ,因此未必可信
| 成员 | 说明 | 示例 |
|---|---|---|
| getClientOriginalName() | 返回上传文件的原始名称 | - |
| getClientOriginalExtension() | 返回上传文件的后缀名 | - |
| getClientMimeType() | 返回上传文件的 MIME 类型 | - |
| guessClientExtension() | 返回上传文件的后缀名 | - |
| getClientSize() | 返回上传文件的字节大小 | - |
| getError() | 返回上传文件的错误信息 ,成功返回 UPLOAD_ERR_OK 常量 ,失败返回 UPLOAD_ERR_XXX 系列的其他常量 | - |
| isValid() | 验证文件是否成功上传 | - |
| move( |
将上传移动到 |
- |
| getMaxFilesize() | 返回 php.ini 中 upload_max_filesize 配置的值 | - |
| getErrorMessage() | 返回上传文件产生的错误信息 | - |
错误常量和错误信息
/**
* Returns an informative upload error message.
*
* @return string The error message regarding the specified error code
*/
public function getErrorMessage()
{
static $errors = array(
UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).',
UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
);
$errorCode = $this->error;
$maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? self::getMaxFilesize() / 1024 : 0;
$message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.';
return sprintf($message, $this->getClientOriginalName(), $maxFilesize);
}
4. Symfony\Component\HttpFoundation\File\File 成员
// SplFileInfo 是 PHP 的原生类
Symfony\Component\HttpFoundation\File\File extends \SplFileInfo;
| 成员 | 说明 | 示例 |
|---|---|---|
| guessExtension() | 根据文件的 MIME 类型返回文件后缀名 ,失败返回 null | - |
| getMimeType() | 返回文件的 MIME 类型 | - |









网友评论