• dropzone


     1.引入css与js文件

    2.建立上传图片的路由到控制器

    3.视图文件form(action到上传路由)与dropzone(参数对应form的ID)选项js如下:

    @extends('layouts.main')
    
    @section('content')
        <h2>Gallery Show</h2>
        <h3>{{ $g->name }}</h3>
        <div class='row'>
            @foreach($g->images as $i)
                <div class='col-sm-3'><img src='upload/gallery_name/image/{{ $i->filename }}'></div>
            @endforeach
        </div>
        <form class='dropzone' action='/image' method="POST" id='addImages'>
            {{ csrf_field() }}
            <input type="hidden" name='gid' value='{{ $g->id }}'>
        </form>
        <a href='/gallery' class='btn btn-primary'>BACK</a>
    @stop
    
    @section('script')
        <script type="text/javascript">
        Dropzone.options.addImages = {
            maxFilesize : 2,
            acceptedFiles: 'image/*'
        };
        </script>
    @stop

    div的请求添加CSRF

        $("#addImages").dropzone({
            url: "/upload/avatar",
            maxFiles: 1,
            maxFilesize: 2,
            acceptedFiles: 'image/*',
            sending: function(file, xhr, formData){
                formData.append('_token', "{!! csrf_token() !!}");
            },
            success: function(file, response){
                console.log(response);
            }
        });

    4.控制器接受请求(验证文件大小、类型),取数据,保存图片,数据入库。最后返回code.

        public function store(Request $request)
        {
            //get the file from the request
            $file = $request->file('file');
            //set my file name
            $name = uniqid() . $file->getClientOriginalName();
            //move the file to correct location
            $success = $file->move('upload/gallery_name/image', iconv('UTF-8', 'GBK', $name));
         if($success){
    //save the image $image = Image::create([ 'gallery_id'=> $request->input('gallery_id'), 'name' => $name, 'created_by' => Auth::user()->id, 'size' => $file->getClientSize(), 'mime' => $file->getClientMimeType(), 'name' => $name ]);
           Response::json('success', 200);
        } return Response::json('error', 400);
    }

    6.JS 回调函数

    <script type="text/javascript">
        Dropzone.options.addImages = {
            maxFilesize : 2,
            acceptedFiles: 'image/*'//The file has been uploaded successfully. Gets the server response as //second argument. (This event was called finished previously) 
            success: function(file, response){
                 if ( ...){}
                 else{}
            }  
        };
        </script>

    参考  http://maxoffsky.com/code-blog/howto-ajax-multiple-file-upload-in-laravel/

  • 相关阅读:
    go系列(6)- beego日志模块的使用
    shell学习(8)- ulimit调优系统参数
    新年开工
    No module named yum错误的解决办法
    如何杀死defunct进程
    图灵机器人微信自动聊天功能
    go系列(5)- beego自己写controller
    Hadoop/Spark 集群都启动了哪些 Java 程序
    Spark 不允许在 Worker 中访问 SparkContext
    Spark 安装
  • 原文地址:https://www.cnblogs.com/fenle/p/4919013.html
Copyright © 2020-2023  润新知