Laravel 5.1 Ajax上傳圖片方法

最近在作的項目基於Laravel 5.1開發,須要用到Ajax上傳,查了些資料,本身整理了下可用的方法。php

控制器:

UploadController.phpcss

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use YuanChao\Editor\EndaEditor;
use Redirect, Input, 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 = '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
            ]
        );
    }
}

模板:

upload_img.blade.phphtml

<!-- 上傳圖片div /S-->
<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::open( array('url' =>['/admin/upload_img'], 'method' => 'post', 'id'=>'imgForm', 'files'=>true) ) !!}
        <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::close()!!}
    </div>
    <div class="panel-footer">
    </div>
</div>

<!-- 上傳圖片div /E-->

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;
}

JS:

須要jQuery庫 和jQuery.form.jsajax

$(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.pic);
        }
    }

})

路由:

//圖片上傳
Route::post('upload_img','UploadController@imgUpload');

如今須要在模板中include 上傳圖片模板json

(個人放在admin目錄下的common目錄下,根據本身放的位置更改)app

@include('admin.common.upload_img')

如今我在create.blade.php中使用dom

<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="">
        <input type="hidden" name="logo" value="">
   </div>
</div>

效果以下圖:ide

1.未上傳狀態post

未上傳狀態

2.點擊上傳ui

點擊上傳

3.上傳完成

上傳完成

有問題能夠在下面留言

原文地址:Laravel 5.1 Ajax上傳圖片方法

相關文章
相關標籤/搜索