1. 程式人生 > 其它 >thinkphp6-本地檔案上傳

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    驗證影象檔案的尺寸和型別