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/