laravel文件存储的使用(文件上传)

资料

laravel学院讲解
链接

文件存储配置(具体配置可以看官网讲解这里我们使用默认):

文件系统的配置文件位于 config/filesystems.php 。
在这个文件中你可以配置所有「磁盘」。
每个磁盘代表特定的存储驱动及存储位置。
每种支持的驱动程序的示例配置都包含在配置文件中。

公共磁盘链接

你可以使用`Artisan` 命令`storage:link`来创建符号链接:

php artisan storage:link

2.使用路由

Route::get('save','SaveController@put');
Route::get('get','SaveController@get');
Route::get('delete','SaveController@delete');
Route::get('download','SaveController@download');

2.1use类:

use IlluminateSupportFacadesStorage;

2.3简单的在控制器中的使用:

 public function put()
    {
        Storage::put('test.txt', '我是测试文字');#保存.txt文件,参数2,保存文字内容
    }

    public function delete()
    {
        Storage::delete('test.txt');#删除已经保存的test.txt文件
    }

    public function get()
    {
        return Storage::get('test.txt');#得到test.txt的内容
    }
    public function download(){
        return Storage::download('test.txt');#下载test.txt文件
    }

下面来看一下实际中的使用过程:

 public function  upload(Request $request){
        if ($request->isMethod('post')){
           $img=$request->file('file');
           //获取图片的扩展名
            $name=$img->getClientOriginalExtension();
           //获取文件的绝对路径
            $path=$img->getRealPath();
            //定义新的文件名
            $filename=date('Y-m-d-h-i-s').'.'.$name;
         Storage::disk('public')->put($filename,file_get_contents($path));
        }
    }

自定义文件上传驱动位置

config/filesystems.php下的disks中自定义

使用

Route::post('uploads_file', function () {
    #实现自定义文件上传
    $file = request()->file('file');
    //获取文件的扩展名
    $name = $file->getClientOriginalExtension();
    //获取文件的绝对路径
    $path = $file->getRealPath();
    //定义新的文件名
    $filename = date('Y-m-d-h-i-s') . '.' . $name;

    dd(Storage::disk('file')->put($filename, file_get_contents($path)));
});

效果展示

自定义下载驱动

我们需要语义化设置存储位置的时候

configfilesystems.php disks中定义 excel驱动

 'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],
        'excel' => [
            'driver' => 'local',#本地驱动
            'root' => storage_path('excel/download'),# 保存的位置
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',#可见性
        ],
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
        ],

    ],
  • 定义对应如下

  • 使用:下载excel文件
public function getExcelImport()
    {
        return Storage::disk('excel')->download('用户管理池导出模板.xlsx');
    }
原文地址:https://www.cnblogs.com/yaoliuyang/p/12895064.html