laravel 结合plupload上传文件到本地

首先定义上传类

class Uploads {
  
  public static function upfiles($files, $path = '', $format_data = false, $add_domain = false) {
    $res = ['errno' => 1, 'errmsg' => '上传图片错误'];
    $data = [];
    foreach($files as $key => $file) {
      //获取后缀
      $ext = strtolower($file->extension());
      $exts = ['jpg', 'png', 'gif', 'jpeg', 'mp4', 'avi', '3gp'];
      //判断后缀是否合法
      if(!in_array($ext, $exts)) {
        $res = ['errno' => 1, 'errmsg' => '请上传正确的图片类型,支持jpg, png, gif, jpeg类型'];
        return json_encode($res);
      } else {
        //生成文件名称
        $filename = time() . str_random(6) . "." . $ext;
        //文件保存路径
        $filepath = 'uploads/';
        if(!empty($path)) {
          $filepath = 'uploads/'. $path .'/';
        }
        if($format_data) {
          $filepath = $filepath . date('Ym') . '/';
        }
        if (!file_exists($filepath)) {
          @mkdir($filepath);
        }
        if($add_domain) {
          $savepath = config('app.url') . $filepath . $filename;
        } else {
          $savepath = $filepath . $filename;
        }
        if ($file->move($filepath, $filename)) {
          $data[] = $savepath;
        }
      }
    }
    $res = ['errno' => 0, 'data' => $data];
    return $res;
  }

  public static function upfile($file, $path = 'images', $format_data = false, $add_domain = false) {
    $res = ['errno' => 1, 'errmsg' => '上传图片错误'];
    $data = '';
     //获取后缀
    $ext = strtolower($file->extension());
    //判断后缀是否合法
    $exts = ['jpg', 'png', 'gif', 'jpeg', 'mp4', 'avi', '3gp'];
    if(!in_array($ext, $exts)) {
      $res = ['errno' => 1, 'errmsg' => '请上传正确的图片类型,支持jpg, png, gif, jpeg类型'];
      return json_encode($res);
    } else {
       //生成文件名称
      $filename = time() . str_random(6) . "." . $ext;
      //文件保存路径
      $filepath = 'uploads/';
      if(!empty($path)) {
        $filepath = 'uploads/'. $path .'/';
      }
      if($format_data) {
        $filepath = $filepath . date('Ym') . '/';
      }
      if (!file_exists($filepath)) {
        @mkdir($filepath);
      }
      if($add_domain) {
        $savepath = config('app.url') . $filepath . $filename;
      } else {
        $savepath = $filepath . $filename;
      }
      if ($file->move($filepath, $filename)) {
        $data = $savepath;
      }
    }
    $res = ['errno' => 0, 'data' => $data];
    return $res;
  }

}

 

前端js

g_object_name = ''
g_object_names = new Array() //多图片上传保持
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000;
currentUrl = window.location.href;
backendIndex = currentUrl.indexOf('backend');
baseBackend = currentUrl.substr(0, backendIndex);


$(document).ready(function() {
    //上传
    $('.media-picker').each(function() {
        var el = $(this);
        var elbtn = el.find('.media-picker-button');
        var multi_selection = false;
        // 上传目录
        var inputField = el.find('input[type=hidden]');
        var token = $('input[name="_token"]').val();

        // 是否多文件上传
        if (elbtn.attr('data-multiple') == 'multiple') {
            multi_selection = true;
            // 如果已经有文件
            var oldFiles = inputField.val();
            if (oldFiles != '') {
                var oldFilesArr = $.parseJSON(oldFiles);
                for (var x = 0; x < oldFilesArr.length; x++) {
                    g_object_names.push(oldFilesArr[x]);
                }
            }
        }

        var updir = inputField.attr('data-oss-path');
        var uploader = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            browse_button: elbtn.attr('data-id') + '_uploader',
            url: baseBackend + 'backend/upload',
            file_data_name: 'image',
            multi_selection: multi_selection,
            multipart_params: { 'updir': updir, '_token': token },
            auto_start: true,
            flash_swf_url: '../plupload/js/Moxie.swf',
            silverlight_xap_url: '../plupload/js/Moxie.xap',

            filters: {
                mime_types: [ //只允许上传图片和zip,rar文件
                    { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" },
                    { title: "Video files", extensions: "mp4,3gp" }
                ],
                max_file_size: '10mb', //最大只能上传10mb的文件
                prevent_duplicates: false //不允许选取重复文件
            },

            init: {
                FilesAdded: function(up) {
                    up.start(); //选择完后直接上传
                },

                FileUploaded: function(up, file, info) {
                    if (info.status == 200) {
                        var file_type = file.type;
                        var is_image = file_type.indexOf('image');
                        var is_video = file_type.indexOf('video');
                        // 获取返回德数据
                        var file_infos = $.parseJSON(info.response);
                        var file_name = file_infos.data;

                        if (multi_selection) {
                            // 多文件转为json
                            g_object_names.push(file_name);
                            inputField.val(JSON.stringify(g_object_names));
                            // 把图片显示出来
                            var imageHtml = '';
                            for (var i = 0; i < g_object_names.length; i++) {
                                if (is_image > -1) {
                                    imageHtml += '<li><div class="img-info"><img src="' + baseBackend + '/' + g_object_names[i] + '"/><p>' + g_object_names[i] + '</p><div class="delete-image"> X </div></div></li>';
                                }
                                if (is_video > -1) {
                                    imageHtml += '<li><div class="img-info"><video controls src="' + baseBackend + '/' + g_object_names[i] + '"></video><p>' + g_object_names[i] + '</p><div class="delete-image"> X </div></div></li>';
                                }
                            }
                            el.find('.medias-list ul').html(imageHtml);

                        } else {
                            // 单文件直接用名称, 
                            inputField.val(file_name);
                            g_object_name = file_name
                                // 把图片显示出来
                            var imageHtml = '';
                            if (is_image > -1) {
                                imageHtml = '<li><div class="img-info"><img src="' + baseBackend + '/' + file_name + '"/><p>' + file_name + '</p><div class="delete-image"> X </div></div></li>';
                            }
                            if (is_video > -1) {
                                imageHtml = '<li><div class="img-info"><video controls src="' + baseBackend + '/' + file_name + '"></video><p>' + file_name + '</p><div class="delete-image"> X </div></div></li>';
                            }
                            el.find('.medias-list ul').html(imageHtml);
                        }
                    } else {
                        alert(info.response);
                    }
                },

                Error: function(up, err) {
                    if (err.code == -600) {
                        alert("\n选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小");
                    } else if (err.code == -601) {
                        alert("\n选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型");
                    } else if (err.code == -602) {
                        alert("\n这个文件已经上传过一遍了");
                    } else {
                        alert("\nError xml:" + err.response);
                    }
                }
            }
        })
        uploader.init();
    })

    // 删除
    $('.media-picker').each(function() {
        var el = $(this)
        var inputField = el.find('input[type=hidden]');
        var fileName = inputField.val();
        var elbtn = el.find('.media-picker-button');
        var multi_selection = false;
        // 是否多文件上传
        if (elbtn.attr('data-multiple') == 'multiple') {
            multi_selection = true;
        }
        if (multi_selection) {
            el.on('click', '.delete-image', function() {
                var elDel = $(this);
                // 得到filename
                var currentFileName = elDel.prev('p').html();
                // 删除当前的父级li
                elDel.parent().parent().remove();
                // 重新赋值数组
                var fileNames = new Array();
                if (g_object_names != '') {
                    fileNames = g_object_names;
                } else {
                    fileNames = $.parseJSON(fileName);
                }
                // 去掉数组中的当前值
                for(var i in fileNames) {
                    if(fileNames[i] == currentFileName) {
                      fileNames.splice(i,1);
                       break;
                    }
                }
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                });
                $.ajax({
                    type: "POST",
                    url: baseBackend + "backend/del_upload",
                    data: "filename=" + currentFileName,
                    success: function(msg) {
                        console.log(msg)
                    }
                });
                inputField.val(JSON.stringify(fileNames));
            })
        } else {
            el.on('click', '.delete-image', function() {
                // 显示值为空
                el.find('.medias-list ul').html('');
                inputField.val('');

                // oss删除
                if (g_object_name != '') {
                    fileName = g_object_name;
                }
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                });
                $.ajax({
                    type: "POST",
                    url: baseBackend + "backend/del_upload",
                    data: "filename=" + fileName,
                    success: function(msg) {
                        console.log(msg)
                    }
                });
            })
        }

    })
})

 

wangeditor


now = timestamp = Date.parse(new Date()) / 1000; 
updir = 'details'
currentUrl = window.location.href;
backendIndex = currentUrl.indexOf('backend');
baseBackend = currentUrl.substr(0, backendIndex);

var E = window.wangEditor
var editor = new E('#content')
//editor.customConfig.zIndex = 0
//editor.customConfig.uploadImgHeaders = {
//    'X-CSRF-TOKEN': $('input[name="_token"]').val()
//}
//editor.customConfig.uploadImgServer = '/backend/updetails'
//editor.customConfig.uploadFileName = 'wangpic[]'
//editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024


editor.customConfig.onchange = function (html) {
    $('.wangeditor_value').val(html)
};

editor.create();

var token = $('input[name="_token"]').val();
var uploader = new plupload.Uploader({
  runtimes: 'html5,flash,silverlight,html4',
  browse_button: editor.imgMenuId,
  url: baseBackend + 'backend/upload',
  file_data_name: 'image',
  multi_selection: true,
  multipart_params: { 'updir': updir, '_token': token },
  auto_start: true,
  flash_swf_url: '../plupload/js/Moxie.swf',
  silverlight_xap_url: '../plupload/js/Moxie.xap',

  filters: {
      mime_types : [ //只允许上传图片和zip,rar文件
      { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" }, 
      { title : "video files", extensions : "mp4,3gp" }
      ],
      max_file_size : '10mb', //最大只能上传10mb的文件
      prevent_duplicates : false //不允许选取重复文件
  },

	init: {
    FilesAdded: function(up) {
      up.start(); //选择完后直接上传
    },

		FileUploaded: function(up, file, info) {
      if (info.status == 200)
      {
        var file_type = file.type;
        var is_image = file_type.indexOf('image');
        var is_video = file_type.indexOf('video');
        // 获取返回德数据
        var file_infos = $.parseJSON(info.response);
        var file_name = file_infos.data;
        if(is_image > -1) {
          editor.cmd.do('insertHtml', '<img src="' + baseBackend + file_name + '" style="width: auto; max-width:100%;"/>');
        }
        if(is_video > -1) {
          editor.cmd.do('insertHtml', '<video controls src="' + baseBackend + file_name + '" style="width: auto; max-width:100%;"></video>');
        }
      }
      else
      {
        alter(info.response);
      } 
    },

    Error: function(up, err) {
      if (err.code == -600) {
        alert("\n选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小");
      }
      else if (err.code == -601) {
        alert("\n选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型");
      }
      else if (err.code == -602) {
        alert("\n这个文件已经上传过一遍了");
      }
      else 
      {
        alert("\nError xml:" + err.response);
      }
    }
	}
});

// uploader.init();
editor.config.customUploadInit = uploader.init(); 

 

 

后台上传



    public function upload(Request $request) {
      $files = $request->file("image");
      $updir = $request->input('updir');
      $res = Uploads::upfile($files, $updir);
      return json_encode($res);
    }

    public function del_upload(Request $request) {
      $res = ['errno' => 1, 'errmsg' => '删除失败'];
      $filename = $request->input('filename');
      if(!empty($filename)) {
        @unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $filename);
        $res = ['errno' => 0, 'errmsg' => '删除成功'];
      }
      return json_encode($res);
    }

 

 

 

展开阅读全文

没有更多推荐了,返回首页