2021年1月6日 星期三

laravel ajax

 laravel ajax

============================================================================
web.1.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

//首頁
Route::get('/','MerchandiseController@indexPage');

//使用者
Route::group(['prefix' => 'user'], function(){
    //使用者驗證
    Route::group(['prefix' => 'auth'], function(){
        Route::get('/sign-up', 'UserAuthController@signUpPage');
        Route::post('/sign-up', 'UserAuthController@signUpProcess');
        Route::get('/sign-in', 'UserAuthController@signInpage');
        Route::post('/sign-in', 'UserAuthController@signInProcess');
        Route::get('/sign-out', 'UserAuthController@signOut');
        //Facebook登入
        Route::get('/facebook-sign-in', 'UserAuthController@facebookSignProcess');
        //Facebook登入重新導向授權資料處理
        Route::get('/facebook-sign-in-callback', 'UserAuthController@facebookSignInCallbackProcess');
    });
});

//商品
Route::group(['prefix' => 'merchandise'], function(){
    Route::get('/','MerchandiseController@merchandiseListPage');
    Route::get('/manage','MerchandiseController@merchandiseManageListPage')
        ->middleware(['user.auth.admin']);
    Route::get('/create','MerchandiseController@merchandiseCreateProcess')
        ->middleware(['user.auth.admin']);
    //指定商品
    Route::group(['prefix' => '{merchandise_id}'], function(){
        Route::get('/','MerchandiseController@merchandiseItemPage')
            ->where([
                'merchandise_id' => '[0-9]+',
            ]);
        Route::group(['middleware' => ['user.auth.admin']], function(){
            Route::get('/edit','MerchandiseController@merchandiseItemEditPage');
            Route::put('/','MerchandiseController@merchandiseItemUpdateProcess');
        });
        Route::post('/buy','MerchandiseController@merchandiseItemBuyProcess')
            ->middleware(['user.auth']);
    });
});

//交易
Route::get('/transaction','TransactionController@transactionListPage')
    ->middleware(['user.auth']);

//test
Route::get('/test','TestController@test');

//寄email
Route::get('/warning','WarningController@send');

//Ajax: 顯示資料
Route::get('ajax','AjaxController@ajaxView');
Route::get('getmsg','AjaxController@ajaxData');

//Ajax: Form資料傳送與處理
Route::get('ajax2','AjaxController@ajaxFormView');
Route::post('ajax3','AjaxController@ajaxFormData');

//register
Route::get('sign-up','UserController@signUpPage');
Route::post('sign-up', 'UserController@signUpProcess');

============================================================================
AjaxController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
    //Ajax: 顯示資料
    public function ajaxView(){
        return view('message');
    }

    public function ajaxData(){
        $msg="Ajax 您好 !!";
        return response()->json(['msg'=> $msg]);
    }

    //Ajax: Form資料傳送與處理
    public function ajaxFormView(){
        return view('message2');
    }

    public function ajaxFormData(){
        $nickname = $_POST["nickname"];
        $gender = $_POST["gender"];

        return response()->json(['nickname'=> $nickname,'gender'=> $gender]);
    }
}

============================================================================
message.blade.php

<html>
<head>
<title>Laravel Ajax</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
function getMessage(){
   $.ajax({
      type:'get',
      url:'getmsg',
      data:'_token = {{csrf_token()}}',
      success:function(data){
         $("#msg").html(data.msg);
      }
   });
}

</script>
</head>
<body>
   <div id="msg">xxxxxx</div>
   <p><button onclick="getMessage()">透過 Ajax 傳送訊息</button></p>
</body>
</html>

============================================================================
message2.blade.php

<!DOCTYPE html>
<html>
<head>
    <!-- <meta name="csrf-token" content="{{ csrf_token() }}"> -->
    <title>Ajax: Form資料傳送與處理</title>
</head>
<body>
    <h3>Ajax: Form資料傳送與處理</h3>
    <form id="demo">
        @csrf
        <p>暱稱:<input type="text" name="nickname" id="nickname"></p>
        <p>性別:
        <select name="gender" id="gender">
            <option value="">請選擇</option>
            <option value="男">男</option>
            <option value="女">女</option>
        </select>
        </p>
        <button type="button" id="submitExample">送出</button>
    </form>
    <br>
    <p id="result"></p> <!-- 顯示回傳資料 -->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- 引入 jQuery -->
    <script>
    $(document).ready(function() {
        $("#submitExample").click(function() { //ID 為 submitExample 的按鈕被點擊時
            $.ajax({
                type: "POST", //傳送方式
                url: "ajax3", //傳送目的地
                dataType: "json", //資料格式
                // headers: {
                //     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                // }, //可用data中的_token取代
                // data: { //傳送資料
                //     _token:  '{{csrf_token()}}', //可取代headers的X-CSRF-TOKEN設定
                //     nickname: $("#nickname").val(), //表單欄位 ID nickname
                //     gender: $("#gender").val() //表單欄位 ID gender
                // },
                data: $("#demo").serialize(),
                success: function(data) {
                    if (data.nickname) { //如果後端回傳 json 資料有 nickname
                        // $("#demo")[0].reset(); //重設 ID 為 demo 的 form (表單)
                        $("#result").html('<font color="#007500">您的暱稱為「<font color="#0000ff">' + data.nickname + '</font>」,性別為「<font color="#0000ff">' + data.gender + '</font>」!</font>');
                    } else { //否則讀取後端回傳 json 資料 errorMsg 顯示錯誤訊息
                        $("#demo")[0].reset(); //重設 ID 為 demo 的 form (表單)
                        $("#result").html('<font color="#ff0000">' + data.errorMsg + '</font>');
                    }
                },
                error: function(jqXHR) {
                    $("#demo")[0].reset(); //重設 ID 為 demo 的 form (表單)
                    $("#result").html('<font color="#ff0000">發生錯誤:' + jqXHR.status + '</font>');
                }
            })
        })
    });
    </script>
</body>
</html>

============================================================================
media.blade.php

@extends('layout.master')
@section('content')
        <div class="my-3 my-md-5">
            <div class="container">

                <!-- 標題 -->
                <div class="page-header">
                    <h1 class="page-title">
                        <!--
                        <a class="icon icon-vertical" href="javascript:void(0)" onclick="window.history.go(-1); return false;">
                            <i class="fe fe-chevron-left"></i>
                        </a>-->多媒體中心
                    </h1>
                    <div class="page-subtitle"> ( 剩餘空間 : <span class="text-muted"> {{$space}} GB</span> / {{$media_size}} GB )</div>
                </div>

                <!-- 搜尋 -->
                <div class="row mb-3">
                    <div class="col-12 col-md-8 p-1">
                        <div class="form-inline">
                            <div class="form-group mr-2">
                                <select id="mySelect" class="form-control custom-select w-auto">
                                    <option value="">全部</option>
                                    <option value="p">圖片</option>
                                    <option value="v">影片</option>
                                </select>
                            </div>
                            <div class="input-icon ml-2">
                                <input type="text" id="myInput" placeholder="輸入搜尋文字..." class="form-control">
                                    <span class="input-icon-addon">
                                    <i class="fe fe-search"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-12 col-md-4 p-1 text-right">
                        <a href="upload" class="btn btn-lg btn-green btn-768" role="button">
                        <i class="fa fa-cloud-upload"></i> 上傳</a>
                        <a href="javascript:void(0)" role="button" id="delMedia" class="btn btn-lg btn-danger btn-768">
                        <i class="fe fe-layers"></i> 刪除?</a>
                        <a href="javascript:void(0)" role="button" id="undo" class="btn btn-lg btn-yellow btn-768">
                        <i class="fa fa-reply"></i></a>
                        <a href="javascript:void(0)" role="button" id="delx" class="btn btn-lg btn-danger btn-768" data-toggle="modal" data-target="#delFile2">
                        <i class="fa fa-trash-o"></i></a>
                    </div>
                </div>
                
                <!-- 圖片 -->
                <div class="row row-cards">
                    @foreach($media as $data)
                    <div class="{{$data->media_type}} myTable col-6 col-md-4 col-lg-3 p-1">
                        <!-- 列表 -->
                        <div class="card p-3">
                            @if($media_use[$i] == 0)
                            <label class="imagecheck">
                                <input name="map[]" type="checkbox" class="imagecheck-input" value="{{$data->media_code}}">
                                <figure class="imagecheck-figure">
                                <img src="{{ 'uploads/'.$data->media_thumb }}" class="imagecheck-image">
                                </figure>
                            </label>
                            @endif

                            <!-- <a class="picture" href="{{ 'uploads/'.$data->media_file }}" title="{{ $data->media_directions }}"> -->
                            <a class="{{ ($data->media_type=='p')?'picture':'video' }}" href="{{ 'uploads/'.$data->media_file }}" title="{{ $data->media_directions }}">
                                <img src="{{ 'uploads/'.$data->media_thumb }}" alt="Photo by" class="rounded">
                            </a>

                            <div class="d-flex align-items-center px-2">
                                <div>
                                    <div>{{ $data->media_directions }}</div>
                                    <!-- 1 Kilobyte (KB)=1024 Bytes -->
                                    <small class="d-block text-muted">{{ round(($data->media_size/1024), 2) }} kb</small>
                                </div>
                                <div class="job ml-auto text-muted">
                                    <a href="javascript:void(0)" id="{{ $data->media_code }}" class="editx icon" data-toggle="modal" data-target="#editFile">
                                        <i class="fe fe-edit mr-1"></i></a>
                                    @if($media_use[$i] == 0)
                                        @php
                                            $i++;
                                        @endphp
                                        <a href="javascript:void(0)" id="{{ $data->media_code }}" class="delete icon d-none d-md-inline-block ml-1" data-toggle="modal" data-target="#delFile">
                                            <i class="fe fe-trash-2 mr-1"></i></a>
                                    @else
                                        <span><i class="fe fe-film mr-1"></i>{{ $media_use[$i++] }}</span>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>

                <!-- 分頁 -->
                <div class="pagination justify-content-center">
                    {{ $media->links() }}
                </div>

                <!--
                <nav aria-label="Page navigation example">
                    <ul class="pagination justify-content-center">
                        <li class="page-item disabled">
                            <a class="page-link" href="#" tabindex="-1">Previous</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">1</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">2</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">3</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">Next</a>
                        </li>
                    </ul>
                </nav>
                -->
            </div>
        </div>
      </div>

        <!-- Modal editFile: 修改圖名 -->
        <div class="modal fade" id="editFile" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="media_directions">Destcription</label>
                                <input type="description" class="form-control" id="media_directions" value="">
                            </div>
                            <button type="button" class="save btn btn-primary">Save</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal delFile: 刪除圖片 -->
        <div class="modal fade" id="delFile" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2 class="modal-title text-danger" id="exampleModalLongTitle">Delete File?</h2>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <div>
                                    Are you sure you want to delete this file?
                                </div>
                            </div>
                            <button type="button" class="delete2 btn btn-danger">Yes</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal delFile2: 刪除多個圖片 -->
        <div class="modal fade" id="delFile2" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2 class="modal-title text-danger" id="exampleModalLongTitle">Delete File?</h2>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <div>
                                    Are you sure you want to delete this file?
                                </div>
                            </div>
                            <button type="button" class="delete3 btn btn-danger">Yes</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

<script>
require(["colorbox"], function() {
    $(".picture").colorbox({transition:"fade", maxWidth:'90%', maxHeight:'90%', photo:true, slideshow:false, previous:false, next:false, arrowkey:false, loop:false});
    $(".video").colorbox({iframe:true, innerWidth:'60%', innerHeight:'60%'});
});

$(function(){

$(".imagecheck").hide();
$("#undo").hide();
$("#delx").hide();

//刪除多個媒體
$("#delMedia").click(function(){
    $("#delMedia").hide(); //刪除
    $("#undo").show();
    $(".imagecheck").show(); //圖+checkbox
    $(".rounded").hide(); //圖
    $(".job").hide(); //編輯
});

$("#undo").click(function(){
    $("#delMedia").show(); //刪除
    $("#undo").hide();
    $(".imagecheck").hide(); //圖+checkbox
    $(".rounded").show(); //圖
    $(".job").show(); //編輯
    $("#delx").hide();

    $(".imagecheck-input").prop("checked", false);
});

$(".imagecheck-input").click(function(){
    //checkbox被選取的數量
    var q2=$('input:checkbox[name="map[]"]:checked').length;

    if(q2==0){
        $("#delx").hide();
    }else{
        $("#delx").show();
    }
});

//執行刪除多個媒體
$("#delx").click(function(){
    $(".delete3").click(function(){
        var val = new Array();

        $('input[name="map[]"]:checkbox:checked').each(function(i) {
            val[i] = this.value;
            // alert(val[i]);
        });

        $.ajax({
            type: "POST",
            url: "{{url('delmedia')}}",
            dataType: "json",
            data: {
                _token: '{{csrf_token()}}',
                media_code: val,
            },
            success: function(data) {
                // alert('刪除成功');
                // alert(data.msg);
                location.reload();
            },
            error: function(jqXHR) {
                alert('刪除失敗');
            }
        });
    });
});

//搜尋:select
$("#mySelect").on("change", function() {
    var value = $(this).val().toLowerCase();
    var value_input = $("#myInput").val().toLowerCase();

    $(".myTable").filter(function() {
        if(value=='p' || value=='v'){ //圖片or影片
            $(this).toggle(
                $(this).hasClass(value) && ($(this).text().toLowerCase().indexOf(value_input) > -1)
            )
        }else{ //全部
            $(this).toggle($(this).text().toLowerCase().indexOf(value_input) > -1)
        }
    });
});

//搜尋:input
$("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var value_select = $("#mySelect").val().toLowerCase();

    $(".myTable").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) && $(this).hasClass(value)
    });
});

//刪除單一媒體
$(".delete").click(function(){
    var media_code=this.id;
    // alert(media_code);

    $(".delete2").click(function(){
      $.ajax({
        type: "POST",
        url: "{{url('deletemedia')}}",
        dataType: "json",
        data: {
          _token: '{{csrf_token()}}',
          media_code: media_code,
        },
        success: function(data) {
            // alert('刪除媒體成功');
            // alert(data.msg);
            location.reload();
        },
        error: function(jqXHR) {
          alert('刪除媒體失敗');
        }
      });
    });
});

//修改圖名
$(".editx").click(function(){
    var media_code=this.id;
    // alert(media_code);

    //取值
    $.ajax({
      type: "POST",
      url: "{{url('getmedia')}}",
      dataType: "json",
      data: {
        _token: '{{csrf_token()}}',
        media_code: media_code,
      },
      success: function(data) {
        $('#media_directions').val(data.desc);
      },
      error: function(jqXHR) {
        alert('編輯圖片名稱失敗');
      }
    });

    //修改
    $(".save").click(function(){
      $.ajax({
        type: "POST",
        url: "{{url('updatemedia')}}",
        dataType: "json",
        data: {
            _token: '{{csrf_token()}}',
            media_code: media_code,
            media_directions: $("#media_directions").val(),
        },
        success: function(data) {
            if(data.no==1){
              alert(data.msg);
            }else{
              // alert(data.msg);
              location.reload();
            }
        },
        error: function(jqXHR) {
            alert('編輯圖片名稱失敗');
        }
      })
    });
});


});

</script>

@endsection

============================================================================
MediaController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Image;

class MediaController extends Controller
{
    //多媒體中心: 媒體列表
    public function mediaList(){
        $row_per_page=1000;

        $result=DB::table('media')
            ->where('media_member', session()->get('member_id'))
            ->orderBy('media_create_time', 'DESC')
            ->paginate($row_per_page);

        $resultx=[];
        
        //媒體使用次數(陣列)
        foreach($result as $media){
            array_push($resultx, $this->get_media_used($media->media_code));
        }

        //查詢Playlist file sizes: 總容量限制 level_media_storage (依會員等級不同,由agent設定)
        // $level->level_media_storage
        $level=DB::table('level')
            ->where('level_code', session()->get('member_level'))
            ->first();

        //已使用空間計算(bytes)
        $space=DB::table('media')
            ->where('media_member', session()->get('member_id'))
            ->sum('media_size');

        /*
          *可使用空間:5GB
          1 Byte = 8 Bits
          1 Kilobyte (KB) = 1024 Bytes
          1 Megabyte (MB) = 1024 KB
          1 Gigabyte (GB) = 1024 MB
        */
        $space=round(($space/1024/1024/1024), 2); // GB

        $binding = [
            'user_account' => session()->get('user_account'),
            'member_label' => session()->get('member_label'),
            'media' => $result,
            'media_use' => $resultx, //媒體使用次數(陣列)
            'i' => 0, //media_use陣列的索引初值
            'space' => $space, //已使用空間計算
            'media_size' => $level->level_media_storage, //可使用空間
        ];

        return view('media.media', $binding);
    }

    //媒體使用次數
    public function get_media_used($media){
        $row=DB::table('plays')
            ->where('plays_media', $media)
            ->count();
    
        $row+=DB::table('banner')
            ->where('banner_media', $media)
            ->count();

        return $row;
    }

    public function xmediaList(){
        $row_per_page=1000;

        $result=DB::table('media')
            ->where('media_member', session()->get('member_id'))
            ->orderBy('media_create_time', 'DESC')
            ->paginate($row_per_page);

        $binding = [
            'user_account' => session()->get('user_account'),
            'member_label' => session()->get('member_label'),
            'media' => $result
        ];

        return view('media.media', $binding);
    }

    //列出資料 (ajax)
    public function getMedia(){
        $media_code=request()->input('media_code'); //媒體序號

        $result=DB::table('media')
            ->where('media_code', $media_code)
            ->first();

        $media_directions=$result->media_directions;

        return response()->json(['desc'=>$media_directions]);
    }

    //更新資料 (ajax)
    public function updateMedia(){
        //接收資料
        $input = request()->all();

        //驗證資料
        $rules = [
            'media_code' => [
                'required',
            ],
            'media_directions' => [
                'required',
            ],
        ];

        $validator = Validator::make($input, $rules);

        if($validator->fails()){
            //資料錯誤
            if($validator->errors()->has('media_directions')){
                return response()->json(['no'=>1,'msg'=>'請輸入備註說明']);
            }
        }else{
            //資料正確
            //update資料庫資料
            $media_code=request()->input('media_code');
            $media_directions=request()->input('media_directions');
    
            DB::table('media')
                ->where('media_code', $media_code)
                ->update(['media_directions' => $media_directions]);

            return response()->json(['msg'=>'編輯成功']);
        }
    }

    //刪除單一媒體 (ajax)
    public function deleteMedia(){
        $media_code=request()->input('media_code'); //媒體序號
        
        //查檔名
        $result=DB::table('media')
            ->select('media_file as file','media_thumb as thumb')
            ->where('media_code', $media_code)
            ->first();
        
        //刪除檔案
        $folder='uploads/';
        unlink($folder.$result->file);
        unlink($folder.$result->thumb);

        //刪除資料
        DB::table('media')
            ->where('media_code', $media_code)
            ->delete();

        return response()->json(['msg'=>1]);
    }

    //刪除多個媒體 (ajax)
    public function delMedia(){
        $code=request()->input('media_code'); //媒體序號

        foreach ($code as $media_code){
            //查檔名
            $result=DB::table('media')
                ->select('media_file as file','media_thumb as thumb')
                ->where('media_code', $media_code)
                ->first();
            
            //刪除檔案
            $folder='uploads/';
            unlink($folder.$result->file);
            unlink($folder.$result->thumb);

            //刪除資料
            DB::table('media')
                ->where('media_code', $media_code)
                ->delete();
        }

        return response()->json(['msg'=>1]);
    }

    //上傳檔案
    public function uploadMediaPage(){
        $binding = [
            'user_account' => session()->get('user_account'),
            'member_label' => session()->get('member_label'),
        ];

        return view('media.upload', $binding);
    }

    public function uploadMedia(Request $request){
        //test------------
        // return $request->file('file'); // "C:\\wamp64\\tmp\\phpFF6E.tmp"
        // return $_FILES["file"]; // {"name":"aaa.gif","type":"image/gif","tmp_name":"C:\\wamp64\\tmp\\php5693.tmp","error":0,"size":27535}

        // return $request->file('file')->path(); // "C:\\wamp64\\tmp\\phpFF6E.tmp"
        // return $request->file('file')->extension(); // gif
        
        // return $request->all(); // {"file":{}}
        // return $request->file; // "C:\\wamp64\\tmp\\php48F.tmp"

        //--------------

        $picture = array("gif","jpg","png","jpeg");//圖片格式
        $video = array("mp4");//影片格式
        $image = $request->file('file'); // "C:\\wamp64\\tmp\\phpFF6E.tmp"
        // $image = "";

        $upload_path = 'uploads';
        $upload_path2 = 'uploads/';

        // 200M限制 (單一檔案)
        // 200 Megabytes = 209,715,200 Bytes
        if($image->getSize() > 209715200){ // 200MB
            return response()->json(['no'=>0,'msg'=>'超過單一檔案限制200M,上傳失敗!']);
        }

        /*
        $validation = Validator::make($request->all(), [
            'file' => 'required|array',
            'file.*' => 'required|mimes:mp4,jpeg,png,jpg,gif|max:204800', //200M (200*1024)
        ]);
        */

        // if($validation->passes()){ //驗證成功
        if($image != ""){ //驗證成功
            //--------------------start
            //媒體使用量檢查

            //*查詢Playlist file sizes: 總容量限制 level_media_storage (依會員等級不同,由agent設定)
            // $level->level_media_storage
            $level=DB::table('level')
                ->where('level_code', session()->get('member_level'))
                ->first();

            //*上傳檔案的size
            $total=$image->getSize();

            /*
            foreach($images as $image){
                // $size=$image->getSize();
                $total+=$image->getSize();
            }
            */

            /*
                1 Byte = 8 Bits
                1 Kilobyte (KB) = 1024 Bytes
                1 Megabyte (MB) = 1024 KB
                1 Gigabyte (GB) = 1024 MB
            */
            $total=round(($total/1024/1024/1024), 2); // GB

            //*已使用空間計算(bytes)
            $space=DB::table('media')
                ->where('media_member', session()->get('member_id'))
                ->sum('media_size');

            $space=round(($space/1024/1024/1024), 2); // GB
            
            //已使用空間 + 上傳檔案的size
            $totalx=$total+$space;
            // $totalx=100; //測試用

            if($totalx <= $level->level_media_storage){ //可上傳
                // return $images; // C:\\wamp64\\tmp\\php4F1.tmp
                // return gettype($images); // object
                // return $total;

                //-----------------------

                //多檔上傳

                //重新命名
                $uid = uniqid(); //檔名
                $ImageExt = $image->getClientOriginalExtension(); //副檔名
                $new_name = $uid . '.' . $ImageExt; //新檔名
                $size = $image->getSize(); //要放在 $image->move() 前 (否則會出現錯誤)

                $str=explode('.',$image->getClientOriginalName()); //原始檔名 ccc.jpg
                $directions = $str[0]; //原始檔名去掉副檔名 ccc

                //上傳檔案
                // $upload_path = 'uploads/test'; //測試用
                // $upload_path2 = 'uploads/test/'; //測試用
                $image->move(public_path($upload_path), $new_name);

                //檔案類別 (p:圖片, v:影片)
                $type = (in_array(strtolower($ImageExt), $picture) ? 'p' : (in_array(strtolower($ImageExt), $video) ? 'v' : ''));

                if ($type == 'v') { //影片
                    //影片截圖
                    //linux
                    // $command = 'ffmpeg -ss 5 -i '. $upload_path2 . $new_name . ' -y -f image2 -vframes 1 '. $upload_path2 . $uid .'.jpg';

                    //windows
                    $command = 'C:\ffmpeg\bin\ffmpeg -ss 5 -i '. $upload_path2 . $new_name . ' -y -f image2 -vframes 1 '. $upload_path2 . $uid .'.jpg';
                    exec($command);
                    
                    //製作縮圖
                    $thumb=$this->makeThumb($upload_path2,$uid.'.jpg');
                    // $file_path1=public_path('uploads/'.$uid.'.jpg');
                    // $file_path2=public_path('uploads/s_'.$uid.'.jpg');
                    // $imagex=Image::make($file_path1)->fit(500,333)->save($file_path2);
                    // unlink($upload_path2,$uid.'.jpg'); //刪圖失敗
                    // $thumb = 's_' . $uid . '.jpg';

                    //取得影片長度 (秒)
                    //composer require james-heinrich/getid3
                    $videofile = $upload_path2 . $new_name;
                    $getID3 = new \getID3; //一定要加反斜線 \
                    $fileData = $getID3->analyze($videofile);
                    $second = round($fileData["playtime_seconds"]); //媒體秒數

                    //刪除影片截圖
                    // unlink($upload_path2, $uid.'.jpg'); //刪圖失敗
                }else{ //圖片
                    $picture_array = getimagesize($upload_path2 . $new_name);

                    if (isset($picture_array['channels']) && $picture_array['channels'] != 3) {
                        return response()->json(['no'=>0,'msg'=>'上傳的圖片檔不是RGB格式']);
                    }

                    //製作縮圖
                    $thumb=$this->makeThumb($upload_path2,$new_name);

                    //媒體秒數
                    $second=0;
                }

                //寫入資料庫
                $code = uniqid();
                $tag = '';
                $file_md5 = md5_file($upload_path2 . $new_name);
                
                $directions = $str[0];
                $time = date("Y-m-d H:i:s");
                $user = session()->get('user_id');
                $member = session()->get('member_id');
                
                $mediax=[
                    'media_code'=>$code,
                    'media_type'=>$type,
                    'media_file'=>$new_name,
                    'media_file_md5'=>$file_md5,
                    'media_thumb'=>$thumb,
                    'media_size'=>$size,
                    'media_second'=>$second,
                    'media_directions'=>$directions,
                    'media_tag'=>$tag,
                    'media_member'=>$member,
                    'media_user'=>$user,
                    'media_create_time'=>$time,
                ];

                DB::table('media')->insert($mediax);

                // return 'upload file ok2';
                return response()->json(['no'=>1,'msg'=>'上傳成功!']);

                //-----------------------

                /*
                return response()->json([
                    'message'   => 'Image Upload Successfully',
                    'uploaded_image' => '<img src="/images/'.$new_name.'" class="img-thumbnail" width="300" />',
                    'class_name'  => 'alert-success'
                ]);
                */
    
                // $md=$request->file('file');
                // $md=$request->file->path();
                // $md=$_FILES["file"]["size"];
                // $md=$_FILES["file"]["name"];
                // $md=session()->get('user_id');
                // $md="$user $member $thumb";
                // return response()->json(['msg'=>$directions]);
    
                // return response()->json(['msg'=>'上傳成功']);

            }else{ //不可上傳
                return response()->json(['no'=>0,'msg'=>'超過使用空間限制,上傳失敗!']);
            }
            //--------------------end
        }else{ //驗證失敗
            /*
            return response()->json([
                'message'   => $validation->errors()->all(),
                'uploaded_image' => '',
                'class_name'  => 'alert-danger'
            ]);
            */

            // return response()->json(['msg'=>$validation->errors()->all()]);
            return response()->json(['msg'=>'上傳失敗']);
        }

        // return response()->json(['msg'=>'上傳成功']);
    }

    //Intervention Image 等比例縮圖在固定範圍(500*333)
    public function makeThumb($upload_path, $img){
    // public function test(){
        // $upload_path='uploads/'; //上傳資料夾
        // $img='22222.jpg'; //原始圖名稱
    
        $thumb = 's_' . $img; //縮圖名稱 (s_22222.jpg)
        $filename = $upload_path . $img; //原始圖: 上傳資料夾+原始圖名稱 (uploads/22222.jpg)
        $filename2 = $upload_path . $thumb; //縮圖: 上傳資料夾+縮圖名稱 (uploads/s_22222.jpg)
    
        //1.等比例縮圖
        $img=Image::make($filename); //uploads/22222.jpg
        $img->resize(500, 333, function ($constraint) {
            // 等比例縮放:若兩個寬高比例與原圖不符的話,會以最短邊去做等比例縮放
            $constraint->aspectRatio();
        })->save($filename2); //uploads/s_22222.jpg
    
        //2.縮圖(小於或等於白色背景圖)與白色背景圖合併(500*333)
        $img2 = Image::canvas(500, 333, '#fff'); //白色背景圖 (自動產生白色背景圖)
        $img2->insert($filename2, 'center')->save($filename2); //uploads/s_22222.jpg
    
        // $img2=Image::make('uploads/white.jpg'); //白色背景圖 white.jpg 500*333 (要先準備圖片white.jpg)
        // $img2->insert($filename2, 'center')->save($filename2); //uploads/s_22222.jpg

        //銷毀圖像(釋放當前圖像實例相關的記憶體)
        // $img->destroy();
        // $img2->destroy();
    
        return $thumb;
    }

    public function test4(){
        //white.jpg + xxx.png ??
        $img=Image::make('uploads/22222.jpg');
        $img->resize(500, 333, function ($constraint) {
            // 等比例縮放:若兩個寬高比例與原圖不符的話,會以最短邊去做等比例縮放
            $constraint->aspectRatio();
        })->save('uploads/22222x.jpg');

        // $img2=Image::make('uploads/white.jpg'); //白色背景圖 500*333
        // $img2->insert('uploads/444x.gif', 'center')->save('uploads/444x.gif');

        $img2 = Image::canvas(500, 333, '#fff'); //白色背景圖
        $img2->insert('uploads/22222x.jpg', 'center')->save('uploads/22222x.jpg');
    }

    public function test3(){
        //Intervention Image 等比例縮圖在固定範圍

        //1.縮圖
        // 固定寬 500px, 高 333px,寬度等比例縮放
        $img=Image::make('uploads/22222.jpg');
        $img->resize(500, 333, function ($constraint) {
            // 等比例縮放:若兩個寬高比例與原圖不符的話,會以最短邊去做等比例縮放
            $constraint->aspectRatio();
        })->save('uploads/22222x.jpg');

        //2.縮圖與白色背景圖合併
        //白色背景圖(500*333)+等比例縮圖(小於或等於白色背景圖)
        //圖檔大小要等於500*333
        $img2=Image::make('uploads/white.jpg'); //白色背景圖 500*333
        $img2->insert('uploads/22222x.jpg', 'center')->save('uploads/22222x.jpg');

        // return 'xcddff';
    }

    //測試   http://localhost/test
    public function test2(){
        //Imagick縮圖
        // phpinfo();
        $filename = 'uploads/5cf75b058ee0f.jpg';
        $upload_path='uploads/';
        $thumb = 's_5cf75b058ee0f.jpg';

        $simg = new \Imagick($filename);
        $simg->setImageBackgroundColor('#FFFFFF');
        $simg = $simg->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);


        $simg->thumbnailImage(500, 333, true, true);
        $simg->writeImage($upload_path . $thumb);

        return $thumb;
    }

    public function test1(){
        //取得影片長度 (秒)
        //composer require james-heinrich/getid3

        // $videofile = 'uploads/5cf5e566f3c4d.mp4';
        $videofile = 'uploads/5cf617c53ad8d.mp4';

        $getID3 = new \getID3; //一定要加反斜線 \
        $fileData = $getID3->analyze($videofile);
        $second = round($fileData["playtime_seconds"]);

        return $second;
    }

    public function xuploadMedia(Request $request){
        /*
            $_FILES["file"]["name"]:上傳檔案的原始名稱。
            $_FILES["file"]["type"]:上傳的檔案類型。
            $_FILES["file"]["size"]:上傳的檔案原始大小。
            $_FILES["file"]["tmp_name"]:上傳檔案後的暫存資料夾位置。
            $_FILES["file"]["error"]:如果檔案上傳有錯誤,可以顯示錯誤代碼。(無錯誤的代碼為0)
        */

        $a1=$_FILES["file"]["name"];
        $a2=$_FILES["file"]["type"];
        $a3=$_FILES["file"]["size"];
        $a4=$_FILES["file"]["tmp_name"];
        $a5=$_FILES["file"]["error"];
        
        //單一檔案上傳
        // move_uploaded_file($_FILES["file"]["tmp_name"], public_path('uploads/').$_FILES["file"]["name"]);

        //多檔案上傳
        // $images = $request->file('file');
        // $a6=$_FILES["file"]["name"][0].','.$_FILES["file"]["name"][1];

        $validation = Validator::make($request->all(), [
            'file' => 'required|array',
            'file.*' => 'required|mimes:mp4,jpeg,png,jpg,gif|max:204800', //200M (200*1024)
        ]);

        if($validation->passes()){ //驗證成功
            $images = $request->file('file');
            $upload_path = 'uploads';

            foreach($images as $image){
                //重新命名
                $uid = uniqid(); //檔名
                $ImageExt = $image->getClientOriginalExtension(); //副檔名
                $new_name = $uid . '.' . $ImageExt; //新檔名

                //上傳檔案
                $image->move(public_path($upload_path), $new_name);
            }

            // return response()->json(['msg'=>$a6]);
            return response()->json(['msg'=>'上傳成功']);
        }else{
            return response()->json(['msg'=>$validation->errors()->all()]);
        }

    }
}

============================================================================
AjaxUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class AjaxUploadController extends Controller
{
    function index(){
        return view('ajax_upload');
    }

    function action(Request $request){
     $validation = Validator::make($request->all(), [
        // 'select_file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        // 'select_file' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        'select_file' => 'required'
     ]);
    
     if($validation->passes()){
        $image = $request->file('select_file');
        $new_name = rand() . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('uploads'), $new_name);

        return response()->json([
            'message'   => 'Image Upload Successfully',
            'uploaded_image' => '<img src="/uploads/'.$new_name.'" class="img-thumbnail" width="300" />',
            'class_name'  => 'alert-success'
        ]);
     }else{
        return response()->json([
            'message'   => $validation->errors()->all(),
            'uploaded_image' => '',
            'class_name'  => 'alert-danger'
        ]);
     }
    }
}

/*
http://127.0.0.1:8000/ajax_upload
*/

============================================================================

沒有留言:

張貼留言