前端插件代码:
- <!--插件-->
- <div id="uploader-demo">
- <!--用来存放item-->
- <div id="fileList" class="uploader-list"></div>
- <div id="filePicker">选择图片</div>
- </div>
- <link rel="stylesheet" type="text/css" href="{$Think.PUBLIC_JS_URL}/webuploader0.1.5/webuploader.css">
- <script type="text/javascript" src="{$Think.PUBLIC_JS_URL}/webuploader0.1.5/webuploader.js"></script>
- <script>
- var $list=$("#fileList"); //这几个初始化全局的百度文档上没说明,好蛋疼
- var thumbnailWidth = 500; //缩略图高度和宽度 (单位是像素),当宽高度是0~1的时候,是按照百分比计算,具体可以看api文档
- var thumbnailHeight = 500;
- // 初始化Web Uploader
- var uploader = WebUploader.create({
- // 选完文件后,是否自动上传。
- auto: true,
- // swf文件路径
- swf: "{$Think.PUBLIC_JS_URL}/webuploader0.1.5/Uploader.swf", //加载swf文件,路径一定要对
- // 文件接收服务端。
- server: 'index.php?s=Admin/CustomService/uploadImg',
- // 选择文件的按钮。可选。
- // 内部根据当前运行是创建,可能是input元素,也可能是flash.
- pick: '#filePicker',
- // 只允许选择图片文件。
- accept: {
- title: 'Images',
- extensions: 'gif,jpg,jpeg,bmp,png',
- mimeTypes: 'image/'
- }
- });
- //上传完成事件监听
- uploader.on( 'fileQueued', function(file) {
- //如发ajax,获取上传图片的地址通过设置属性显示出来
- $.ajax({
- url: "index.php?s=Admin/CustomService/showCustomServiceImg",
- success: function($data) {
- console.log($data);
- // $('#showImg').attr('src',$data); //设置属性显示图片
- if($data !== ''){
- alert('上传成功,请刷新页面');
- }
- }
- });
- });
后端php原生上传代码:
- /**
- * 原生上传图片
- */
- public function uploadImg(){
- $file = $_FILES['file']; //接收上传的图片
- if($file['error'] == 0){
- $savePath = DIR_MANAGE_PATH; //群名片绝对路径配置
- _mkdir($savePath); //常量中的路径,文件不存在则创建
- //效验文件大小
- if($file['size'] > 3145728){
- $this->ajaxRtn(402,'图片大于3M');
- exit;
- }
- //效验文件格式
- $fileType = explode('/',$file['type']);
- if(array_key_exists($fileType[1],['jpg','png'])){
- $this->ajaxRtn(403,'图片类型不对');
- exit;
- }
- $filePath = DIR_MANAGE_PATH.'/'.rand(1111,9999).'.png'; //上传到哪个位置
- $uploadRes = move_uploaded_file($file['tmp_name'],$filePath); //【关键在这,上传文件】
- if($uploadRes){ //文件上传成功
- $obj = new \Think\Model('img'); //入库
- $data['img'] = $filePath;
- $res = $obj->add($data);
- //echo $obj->getLastSql();
- $this->ajaxRtn(200,$filePath); //上传成功返回图片地址,以供显示
- if(!$res){
- $this->ajaxRtn(400,'上传失败');
- }
- }
- }else{
- $this->ajaxRtn(401,'上传错误');
- }
- }
- /**
- * 返回状态码
- * @param $code 状态码
- * @param $message 信息
- */
- public function ajaxRtn($code,$message){
- $msg = ['code'=>$code,'msg'=>$message];
- echo json_encode($msg);
- }