1. 程式人生 > >Laravel 5 - 文件上傳

Laravel 5 - 文件上傳

gin oot 存儲空間 alt pub ems mit part 方便

一、簡介

Laravel 有很棒的文件系統抽象層,是基於 Frank de Jonge 的 Flysystem 擴展包。 Laravel 集成的 Flysystem 提供了簡單的接口,可以操作本地端空間、 Amazon S3 、 Rackspace Cloud Storage 。更方便的是,它可以非常簡單的切換不同保存方式,但仍使用相同的 API 操作!

默認使用本地端空間。當然,你也可以設置多組磁盤,甚至在多個磁盤使用相同的驅動。Laravel文件系統提供了非常強大的功能,但是本文只介紹常用的文件上傳功能。

本文通過介紹使用本地端空間來介紹Laravel中文件上傳的使用。

二、配置

文件系統的配置文件在 config/filesystems.php 文件中,此處我們新建一個uploads本地磁盤空間用於存儲上傳的文件,具體配置項及說明如下:

技術分享圖片
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "ftp", "s3", "rackspace"
    |
    */

    // 默認使用本地端空間 支持 "local", "ftp", "s3", "rackspace"
    ‘default‘ => ‘local‘,

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    // 雲存儲使用 Amazon S3
    ‘cloud‘ => ‘s3‘,

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    ‘disks‘ => [

        // 本地端的local空間
        ‘local‘ => [
            ‘driver‘ => ‘local‘,
            ‘root‘ => storage_path(‘app‘),
        ],

        // 本地端的public空間
        ‘public‘ => [
            ‘driver‘ => ‘local‘,
            ‘root‘ => storage_path(‘app/public‘),
            ‘visibility‘ => ‘public‘,
        ],

        // 新建一個本地端uploads空間(目錄) 用於存儲上傳的文件
        ‘uploads‘ => [

            ‘driver‘ => ‘local‘,

            // 文件將上傳到storage/app/uploads目錄
            ‘root‘ => storage_path(‘app/uploads‘),

            // 文件將上傳到public/uploads目錄 如果需要瀏覽器直接訪問 請設置成這個
            //‘root‘ => public_path(‘uploads‘),
        ],

        // Amazon S3 相關配置
        ‘s3‘ => [
            ‘driver‘ => ‘s3‘,
            ‘key‘ => ‘your-key‘,
            ‘secret‘ => ‘your-secret‘,
            ‘region‘ => ‘your-region‘,
            ‘bucket‘ => ‘your-bucket‘,
        ],

    ],

];
技術分享圖片

三、代碼實現文件上傳

1. 控制器代碼

技術分享圖片
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Storage;


class FileController extends Controller
{

    // 文件上傳方法
    public function upload(Request $request)
    {

        if ($request->isMethod(‘post‘)) {

            $file = $request->file(‘picture‘);

            // 文件是否上傳成功
            if ($file->isValid()) {

                // 獲取文件相關信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 擴展名
                $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                $type = $file->getClientMimeType();     // image/jpeg

                // 上傳文件
                $filename = date(‘Y-m-d-H-i-s‘) . ‘-‘ . uniqid() . ‘.‘ . $ext;
                // 使用我們新建的uploads本地存儲空間(目錄)
                //這裏的uploads是配置文件的名稱
                $bool = Storage::disk(‘uploads‘)->put($filename, file_get_contents($realPath));
                var_dump($bool);

            }

        }

        return view(‘upload‘);
    }
}    
技術分享圖片

2-1.upload.blade.php 模板代碼(上傳組件為bootstrap-fileinput)如果太亂,可以看下面的最簡單的頁面:

技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
<link rel="stylesheet"  href="/static/layui-v2.1.7/css/layui.css" />
<script src="/static/layui-v2.1.7/layui.js"></script>
<link rel="stylesheet" href="/static/css/bootstrap-4.0.0-beta.2/css/bootstrap.min.css" />
<script src="/static/js/jquery/jquery-3.2.1.min.js"></script>
<script src="/static/js/popper/popper.min.js"></script>
<script src="/static/css/bootstrap-4.0.0-beta.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/css/index.css" /> <link href="/static/bootstrap-fileinput/css/fileinput.css" media="all" rel="stylesheet" type="text/css"/> <link href="/static/css/font-awesome-4.7.0/css/font-awesome.min.css" media="all" rel="stylesheet" type="text/css"/> <link href="/static/bootstrap-fileinput/themes/explorer-fa/theme.css" media="all" rel="stylesheet" type="text/css"/> <script src="/static/bootstrap-fileinput/js/plugins/sortable.js" type="text/javascript"></script> <script src="/static/bootstrap-fileinput/js/fileinput.js" type="text/javascript"></script> <script src="/static/bootstrap-fileinput/js/locales/zh.js" type="text/javascript"></script> <script src="/static/bootstrap-fileinput/themes/explorer-fa/theme.js" type="text/javascript"></script> <script src="/static/bootstrap-fileinput/themes/fa/theme.js" type="text/javascript"></script> <title>報表上傳</title> </head> <body> <div class="layui-body"> <div style="padding: 15px;"> <blockquote class="layui-elem-quote"> 報表上傳 </blockquote> </div> <div class="container"> <div class="container kv-main"> <form enctype="multipart/form-data" method="post"> <label class="control-label">Select File</label> <input id="input-b5" name="input-b5" type="file" multiple> {{ csrf_field() }} </form> </div> </div> </div> </body> <script> $(document).ready(function(){ $("#input-b5").fileinput({ showCaption: false, theme: ‘fa‘, language: ‘zh‘, uploadUrl: ‘./upload‘, allowedFileExtensions: [‘jpg‘, ‘png‘, ‘gif‘] }); }); $.ajaxSetup({ headers: { ‘X-CSRF-TOKEN‘: $(‘meta[name="csrf-token"]‘).attr(‘content‘) } }); </script> </html>
技術分享圖片

2-2. 最基礎的 upload.blade.php 模板代碼:

<form method="post" enctype="multipart/form-data" >    
    <input type="file" name="picture">
    <button type="submit"> 提交 </button>
</form>

Laravel 5 - 文件上傳