文件上传


brandonsavage/Upload

项目地址

https://github.com/brandonsavage/Upload

安装

composer require brandonsavage/Upload

具体上传请参考该项目

下面是老的上传类(已废弃)

上传单张图片,以上传一个课程封面为例

html页面代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <p><input type="file" name="cover" /></p>
        <p><input type="submit" value="上传" /></p>
    </form>
</body>

PHP代码

<?php
namespace app\api\controller;

use Timo\Core\App;use Timo\Helper;
use Timo\UploadFiles;

class Course
{
    function uploadCover($course_id)
    {
        $upload = new UploadFiles();
        $four_path = Helper::getFourPath($course_id); // 000/00/10/09/
        $relative_path = 'course/cover/' . $four_path; // course/cover/000/00/01/00/
        $file_dir = ROOT_PATH . $relative_path;
        $ret = $upload->upload('cover', $file_dir);
        
        if (!$ret) {
            App::result(1, $upload->getErrorInfo());
        }
        
        $file = $upload->getSuccessInfo()[0];
        return App::result(0, '上传成功', [
            'file' => $file
        ]);
    }
}

上传多张图片

html页面代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <p><input type="file" name="cover[]" /></p>
        <p><input type="file" name="cover[]" /></p>
        <p><input type="file" name="cover[]" /></p>
        <p><input type="submit" value="上传" /></p>
    </form>
</body>

PHP代码

$upload = new UploadFiles();
$ret = $upload->upload('cover', $file_dir);
if (!$ret) {
    return false;
}
$files = $upload->getSuccessInfo()
print_r($files);

输出如下:

Array
(
    [0] => Array
        (
            [name] => 57d7900d264b9.jpg
            [type] => image/jpeg
            [tmp_name] => C:\Windows\Temp\phpBA9C.tmp
            [error] => 0
            [size] => 31051
            [extension] => jpg
            [savepath] => E:\store\TimoPHP\wwwroot\web\static\homework\000\00\01\99\
            [savename] => 5809b14e2fa5c1486.jpg
        )

    [1] => Array
        (
            [name] => 01191439710123.jpg
            [type] => image/jpeg
            [tmp_name] => C:\Windows\Temp\phpBAAD.tmp
            [error] => 0
            [size] => 30127
            [extension] => jpg
            [savepath] => E:\store\TimoPHP\wwwroot\web\static\homework\000\00\01\99\
            [savename] => 5809b14e2fe448387.jpg
        )

    [2] => Array
        (
            [name] => 20160929123459.png
            [type] => image/png
            [tmp_name] => C:\Windows\Temp\phpBAAE.tmp
            [error] => 0
            [size] => 18165
            [extension] => png
            [savepath] => E:\store\TimoPHP\wwwroot\web\static\homework\000\00\01\99\
            [savename] => 5809b14e3022c4328.png
        )
)