1. 程式人生 > >Larvel5.2上傳圖片並顯示縮圖

Larvel5.2上傳圖片並顯示縮圖

1.建立控制器UploadController.php

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Redirect, Response;
class UploadController extends Controller {

	 //Ajax上傳圖片
    public function imgUpload()
    {
        $file = Input::file('file');
        $id = Input::get('id');
        $allowed_extensions = ["png", "jpg", "gif"];
        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
            return ['error' => 'You may only upload png, jpg or gif.'];
        }

        $destinationPath = 'lib/uploads/images/';
        $extension = $file->getClientOriginalExtension();
        $fileName = str_random(10).'.'.$extension;
        $file->move($destinationPath, $fileName);
        return Response::json(
            [
                'success' => true,
                'pic' => asset($destinationPath.$fileName), //這裡返回的是檔案地址+檔名
                'id' => $id,
                'fname' => $fileName, //這裡返回的是檔名
            ]
        );
    }

    
}
2.註冊路由
 //圖片上傳
    Route::post('upload_img','UploadController@imgUpload');

3.編寫upload.css,放到public/lib/css(資料夾需要自己建)
.thumb-wrap{
    overflow: hidden;
}
.thumb-wrap img{
    margin-top: 10px;
}
.pic-upload{
    width: 100%;
    height: 34px;
    margin-bottom: 10px;
}
#thumb-show{
    max-width: 100%;
    max-height: 300px;
}
.upload-mask{
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,.4);
    z-index: 1000;
}
.upload-file .close{
    cursor: pointer;
    font-size: 14px;
}

.upload-file{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -105px;
    margin-left: -150px;
    max-width: 300px;
    z-index: 1001;
    display: none;
}

.upload-mask{
    display: none;
}

4.在resource/views/建立模板upload_img.blade.php,form要老老實實的用標籤寫,否則報錯
<div class="upload-mask">
</div>
<div class="panel panel-info upload-file">
    <div class="panel-heading">
        上傳圖片
        <span class="close pull-right">關閉</span>
    </div>
    <div class="panel-body">
        <div id="validation-errors"></div>
        <form action="{{ URL('upload_img') }}" method='post' enctype="multipart/form-data" id='imgForm'>
        
        <div class="form-group">
            <label>圖片上傳</label>
            <span class="require">(*)</span>
            <input id="thumb" name="file" type="file"  required="required">
            <input id="imgID"  type="hidden" name="id" value="">
           
        </div>
       </form>
    </div>
    <div class="panel-footer">
    </div>
</div>
5.建立上傳的js,可以放到模板upload_img裡面去
    $(function(){
    //上傳圖片相關

    $('.upload-mask').on('click',function(){
        $(this).hide();
        $('.upload-file').hide();
    })

    $('.upload-file .close').on('click',function(){
        $('.upload-mask').hide();
        $('.upload-file').hide();
    })

    var imgSrc = $('.pic-upload').next().attr('src');
    console.log(imgSrc);
    if(imgSrc == ''){
        $('.pic-upload').next().css('display','none');
    }
    $('.pic-upload').on('click',function(){
        $('.upload-mask').show();
        $('.upload-file').show();
        console.log($(this).next().attr('id'));
        var imgID = $(this).next().attr('id');
        $('#imgID').attr('value',imgID);
    })

    //ajax 上傳
    $(document).ready(function() {
        var options = {
            beforeSubmit:  showRequest,
            success:       showResponse,
            dataType: 'json'
        };
        $('#imgForm input[name=file]').on('change', function(){
            //$('#upload-avatar').html('正在上傳...');
            $('#imgForm').ajaxForm(options).submit();
        });
    });

    function showRequest() {
        $("#validation-errors").hide().empty();
        $("#output").css('display','none');
        return true;
    }

    function showResponse(response)  {
        if(response.success == false)
        {
            var responseErrors = response.errors;
            $.each(responseErrors, function(index, value)
            {
                if (value.length != 0)
                {
                    $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
                }
            });
            $("#validation-errors").show();
        } else {

            $('.upload-mask').hide();
            $('.upload-file').hide();
            $('.pic-upload').next().css('display','block');

            console.log(response.pic);
            // 生成圖片地址
            $("#"+response.id).attr('src',response.pic); 
            $("#"+response.id).next().attr('value',response.fname); //我這裡使用的是返回檔名,如果是本地使用,吧fname改成pic

        }
    }

})

6.在需要使用的模版中使用,需要呼叫jquery和jquery.form和upload_img.blade.php檔案
<link href="{{asset('lib/css/upload.css')}}" rel="stylesheet">
<div class="form-group row">
     <label class="col-md-2 control-label">活動圖片</label>
     <div class="col-md-4 thumb-wrap">
     <div class="pic-upload btn btn-block btn-info btn-flat" title="點選上傳">點選上傳</div>
          <img id="logo" src="{{ URL($act->activity_pic) }}" width='50%' height='30%'>
          <input type="hidden" name="logo" value="">
      </div>
 </div>
<script src="{{asset('lib/js/jquery-2.0.3.min.js')}}"></script>
<!-- 圖片上傳的js和引用檔案 -->
<script src="{{asset('lib/js/jquery.form.js')}}"></script>
@include('upload_img')



7.如果function ajaxform(...) doesn't exist,那麼就是你jquery載入了兩次,第二次會覆蓋第一次,去谷歌瀏覽器F12,NETWORK可以看到載入了幾次