thinkphp6-本地文件上傳


用法

配置文件 config/filesystem.php

<?php

return [
    // 默認磁盤
    'default' => env('filesystem.driver', 'local'),
    // 磁盤列表
    'disks'   => [
        'local'  => [
            'type' => 'local',
            'root' => app()->getRuntimePath() . 'storage',
        ],
        'public' => [
            // 磁盤類型
            'type'       => 'local',
            // 磁盤路徑
            'root'       => app()->getRootPath() . 'public/storage',
            // 磁盤路徑對應的外部URL路徑
            'url'        => '/storage',
            // 可見性
            'visibility' => 'public',
        ],
        // 更多的磁盤配置信息
    ],
];

控制器 app/controller/Index.php

<?php
namespace app\controller;


class Index
{
    public function index()
    {
        return view('index');
    }

    public function upload(){
        // 獲取表單上傳文件 例如上傳了001.jpg
        $file = request()->file('image');
        // 上傳到本地服務器
        $savename = \think\facade\Filesystem::putFile( 'topic', $file);
        //$savename = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
        echo $savename;
    }
}

視圖 app/view/index/index.html

<form action="/index/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="image" /> <br>
    <input type="submit" value="上傳" />
</form> 

測試(上傳圖片,查看runtime/storage下是否生成對應文件)

http://127.0.0.1:8000/index

多文件上傳

視圖

<form action="/index/index/upload" enctype="multipart/form-data" method="post">
<input type="file" name="image[]" /> <br> 
<input type="file" name="image[]" /> <br> 
<input type="file" name="image[]" /> <br> 
<input type="submit" value="上傳" /> 
</form>

控制器

public function upload(){
    // 獲取表單上傳文件
    $files = request()->file('image');
    $savename = [];
    foreach($files as $file){
        $savename[] = \think\facade\Filesystem::putFile( 'topic', $file);
    }
}

驗證

public function upload(){
    // 獲取表單上傳文件
    $files = request()->file();
    try {
        validate(['image'=>'fileSize:10240|fileExt:jpg|image:200,200,jpg'])
            ->check($files);
        $savename = [];
        foreach($files as $file) {
            $savename[] = \think\facade\Filesystem::putFile( 'topic', $file);
        }
    } catch (\think\exception\ValidateException $e) {
        echo $e->getMessage();
    }
}

驗證參數

驗證參數    說明
fileSize    上傳文件的最大字節
fileExt    文件后綴,多個用逗號分割或者數組
fileMime    文件MIME類型,多個用逗號分割或者數組
image    驗證圖像文件的尺寸和類型


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM