对百度上传webupload插件的两种写法
第一种调用一个封装好的js
使用方法:
调用mywebupload.js
js实例化
$(function () {
$("#uploaders").powerWebUpload({ auto: false,fileNumLimit:8,hiddenInputId:token });
});
要修改参数等内容,去修改mywebupload.js文件
可以实现图片批量,指定数量,大小,上传发表前删除,等等功能
https://github.com/fex-team/webuploader/releases
参考资料:
http://fex.baidu.com/webuploader/
(function ($, window) {
var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../..";
function SuiJiNum() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function initWebUpload(item, options) {
if (!WebUploader.Uploader.support()) {
var error = "上传控件不支持您的浏览器!请尝试升级flash版本或者使用Chrome引擎的浏览器。<a target='_blank' href='http://se.360.cn'>下载页面</a>";
if (window.console) {
window.console.log(error);
}
$(item).text(error);
return;
}
//创建默认参数
var defaults = {
auto:true,
hiddenInputId: "", // input hidden id
onAllComplete: function (event) { }, // 当所有file都上传后执行的回调函数
onComplete: function (event) { },// 每上传一个file的回调函数
innerOptions: {},
fileNumLimit: undefined,//验证文件总数量, 超出则不允许加入队列
fileSizeLimit: undefined,//验证文件总大小是否超出限制, 超出则不允许加入队列。
fileSingleSizeLimit: undefined,//验证单个文件大小是否超出限制, 超出则不允许加入队列
PostbackHold: false,
};
var opts = $.extend(defaults, options);
var hdFileData = $("#" + opts.hiddenInputId);
var target = $(item);//容器
var pickerid = "";
if (typeof guidGenerator36 != 'undefined')//给一个唯一ID
pickerid = guidGenerator36();
else
pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
var uploaderStrdiv = '<div class="webuploader">'
//debugger
if (opts.auto) {
uploaderStrdiv =
'<div id="Uploadthelist" class="uploader-list"></div>' +
'<div class="btns">' +
'<div id="' + pickerid + '">选择文件</div>' +
'</div>'
} else {
uploaderStrdiv =
'<div class="uploader-list"></div>' +
'<div class="btns">' +
'<div id="' + pickerid + '">选择文件</div>' +
'<button type="button" class="webuploadbtn">开始上传</button>' +
'</div>'
}
//在这里将display的值none修改为了block 因为152行的input的type类型修改为了hidden
uploaderStrdiv += '<div style="display:block" class="UploadhiddenInput" >\
</div>'
uploaderStrdiv+='</div>';
target.append(uploaderStrdiv);
var $list = target.find('.uploader-list'),
$btn = target.find('.webuploadbtn'),//手动上传按钮备用
state = 'pending',
$hiddenInput = target.find('.UploadhiddenInput'),
uploader;
var jsonData = {
fileList: []
};
var webuploaderoptions = $.extend({
// swf文件路径
swf: applicationPath + '/static/bdwebupload/Uploader.swf',
// 文件接收服务端。
server: '/admin/games/upload',
deleteServer:'/admin/games/deletefile',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#' + pickerid,
//不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false,
fileNumLimit: opts.fileNumLimit,
fileSizeLimit: opts.fileSizeLimit,
fileSingleSizeLimit: opts.fileSingleSizeLimit
},
opts.innerOptions);
var uploader = WebUploader.create(webuploaderoptions);
//回发时还原hiddenfiled的保持数据
var fileDataStr = hdFileData.val();
if (fileDataStr && opts.PostbackHold) {
jsonData = JSON.parse(fileDataStr);
$.each(jsonData.fileList, function (index, fileData) {
var newid = SuiJiNum();
fileData.queueId = newid;
$list.append('<div id="' + newid + '" class="item">' +
'<div class="info">' + fileData.name + '</div>' +
'<div class="state">已上传</div>' +
'<div class="del"></div>' +
'</div>');
});
hdFileData.val(JSON.stringify(jsonData));
}
if (opts.auto) {
uploader.on('fileQueued', function (file) {
//debugger;
$list.append('<div id="' + $(item)[0].id + file.id + '" class="item">' +
'<span class="webuploadinfo">' + file.name + '</span>' +
'<span class="webuploadstate">正在上传...</span>' +
'<div class="webuploadDelbtn">删除</div><br />' +
'</div>');
uploader.upload();
});
} else {
uploader.on('fileQueued', function (file) {//队列事件
$list.append('<div id="' + $(item)[0].id + file.id + '" class="item">' +
'<span class="webuploadinfo">' + file.name + '</span>' +
'<span class="webuploadstate">等待上传...</span>' +
'<div class="webuploadDelbtn">删除</div><br />' +
'</div>');
});
}
uploader.on('uploadProgress', function (file, percentage) {//进度条事件
var $li = target.find('#' + $(item)[0].id + file.id),
$percent = $li.find('.progress .bar');
// 避免重复创建
if (!$percent.length) {
$percent = $('<span class="progress">' +
'<span class="percentage"><span class="text"></span>' +
'<span class="bar" role="progressbar" style="width: 0%">' +
'</span></span>' +
'</span>').appendTo($li).find('.bar');
}
$li.find('span.webuploadstate').html('上传中');
$li.find(".text").text(Math.round(percentage * 100) + '%');
$percent.css('width', percentage * 100 + '%');
});
uploader.on('uploadSuccess', function (file, response) {//上传成功事件
//debugger
if (response.state == "error") {
target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html(response.message);
} else {
target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('已上传');
//在这里修改如下,原来的type为text修改为hidden,增加了name值--pan
$hiddenInput.append('<input type="hidden" name="upfile[]" id="hiddenInput'+$(item)[0].id + file.id + '" class="hiddenInput" value="' + response.message + '" />')
}
});
uploader.on('uploadError', function (file) {
target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('上传出错');
});
uploader.on('uploadComplete', function (file) {//全部完成事件
target.find('#' + $(item)[0].id + file.id).find('.progress').fadeOut();
});
uploader.on('all', function (type) {
if (type === 'startUpload') {
state = 'uploading';
} else if (type === 'stopUpload') {
state = 'paused';
} else if (type === 'uploadFinished') {
state = 'done';
}
if (state === 'uploading') {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
}
});
//删除时执行的方法
uploader.on('fileDequeued', function (file) {
//debugger
var fullName = $("#hiddenInput" + $(item)[0].id + file.id).val();
if (fullName!=null) {
$.post(webuploaderoptions.deleteServer, { fullName: fullName }, function (data) {
console.log(data);
})
}
$("#"+ $(item)[0].id + file.id).remove();
$("#hiddenInput" + $(item)[0].id + file.id).remove();
})
//多文件点击上传的方法
$btn.on('click', function () {
if (state === 'uploading') {
uploader.stop();
} else {
uploader.upload();
}
});
//删除
$list.on("click", ".webuploadDelbtn", function () {
//debugger
var $ele = $(this);
var id = $ele.parent().attr("id");
var id = id.replace($(item)[0].id, "");
var file = uploader.getFile(id);
uploader.removeFile(file);
});
}
$.fn.GetFilesAddress = function (options) {
var ele = $(this);
var filesdata = ele.find(".UploadhiddenInput");
var filesAddress = [];
filesdata.find(".hiddenInput").each(function () {
filesAddress.push($(this).val());
})
return filesAddress;
}
$.fn.powerWebUpload = function (options) {
var ele = this;
if (typeof WebUploader == 'undefined') {
var casspath = applicationPath + "/static/bdwebupload/webuploader.css";
$("<link>").attr({ rel: "stylesheet", type: "text/css", href: casspath }).appendTo("head");
var jspath = applicationPath + "/static/bdwebupload/webuploader.min.js";
$.getScript(jspath) .done(function() {
initWebUpload(ele, options);
})
.fail(function() {
alert("请检查webuploader的路径是否正确!")
});
}
else {
initWebUpload(ele, options);
}
}
})(jQuery, window);
使用时要将webupload的的文件夹全部放置在web指定目录,然后引入两个文件
<link rel="stylesheet" type="text/css" href="__STATIC__/bdwebupload/webuploader.css" />
<link rel="stylesheet" type="text/css" href="__STATIC__/bdwebupload/bootstrap.min.css" />
<script type="text/javascript" src="__STATIC__/bdwebupload/webuploader.js"></script>
<script type="text/javascript" src="__STATIC__/bdwebupload/bootstrap.min.js"></script>
<script type="text/javascript" src="__STATIC__/bdwebupload/mywebupload.js"></script>
下面放上html代码
<link rel="stylesheet" type="text/css" href="__STATIC__/bdwebupload/webuploader.css" />
<link rel="stylesheet" type="text/css" href="__STATIC__/bdwebupload/bootstrap.min.css" />
<!-- 配置文件 -->
<script type="text/javascript" src="__STATIC__/editor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="__STATIC__/editor/ueditor.all.js"></script>
<div class="page-wrap">
<!--开始::内容-->
<section class="page-hd">
<header>
<h2 class="title">添加游戏</h2>
<p class="title-description">
请认真填写表单内容
</p>
</header>
<hr>
</section>
<form action="{:url('admin/games/save')}" method="post" enctype="multipart/form-data">
<div class="form-group-col-2">
<div class="form-label">游戏名称:</div>
<div class="form-cont">
<input placeholder="请输入名称" class="form-control form-boxed" name="name" type="text">
</div>
</div>
{:token()}
<div class="form-group-col-2">
<div class="form-label">游戏分类:</div>
<div class="form-cont">
<select style="width:auto;" name="category_id">
{volist name='category' id='category'}
<option value="{$category.id}">{$category.title}</option>
{/volist}
</select>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label">游戏专题:</div>
<div class="form-cont">
<select style="width:auto;" name="special_id">
{volist name='special' id='special'}
<option value="{$special.id}">{$special.title}</option>
{/volist}
</select>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label">推荐(多选):</div>
<div class="form-cont">
<label class="check-box">
<input name="recommend" value="1" type="checkbox">
<span>推荐游戏</span>
</label>
<label class="check-box">
<input name="hotgame" value="1" type="checkbox">
<span>热门游戏</span>
</label>
<label class="check-box">
<input name="newadd" value="1" type="checkbox">
<span>最新游戏</span>
</label>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label">游戏图片</div>
<div class="form-cont">
<div id="uploaders" style="margin-left:10px"></div><span style="color:red"> 注意,最多可上传八张</span>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label">上传游戏</div>
<div class="form-cont">
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker">选择文件</div>
<button id="ctlBtn" type="button" class="btn btn-default">开始上传</button>
</div>
<div id="error"></div>
</div>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label">摘要</div>
<div class="form-cont">
<script id="container" name="content" type="text/plain">在这里编辑游戏详情</script>
</div>
</div>
<div class="form-group-col-2">
<div class="form-label"></div>
<div class="form-cont">
<input class="btn btn-primary" value="提交表单" type="submit">
<input class="btn btn-disabled" value="禁止" type="reset">
</div>
</div>
</form>
<!--开始::结束-->
</div>
<script type="text/javascript" src="__STATIC__/bdwebupload/webuploader.js"></script>
<script type="text/javascript" src="__STATIC__/bdwebupload/bootstrap.min.js"></script>
<script type="text/javascript" src="__STATIC__/bdwebupload/mywebupload.js"></script>
<!-- 实例化编辑器 -->
<script type="text/javascript">
//实例化百度编辑器
var ue = UE.getEditor('container', {
autoHeightEnabled: true,
autoFloatEnabled: true,
initialFrameWidth:950,
initialFrameHeight:400,
});
jQuery(function() {
var $ = jQuery,
$list = $('#thelist'),
$btn = $('#ctlBtn'),
state = 'pending',
uploader,
maxSize = 20,
limit = 1;
uploader = WebUploader.create({
// 不压缩image
resize: false,
// swf文件路径
swf: '/static/bdwebupload/Uploader.swf',
// 文件接收服务端。
server: '__URL__/uploadflash',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
//文件类型限制
accept: {
extensions: 'swf',
},
//允许最多文件数量
fileNumLimit: limit,
//文件大小限制20M
fileSingleSizeLimit: maxSize*1024*1024,
fileVal:'flash',
});
uploader.on("error",function (type,handler){
if (type=="Q_TYPE_DENIED"){
alert('不允许上传的文件的类型');
}else if(type=="F_EXCEED_SIZE"){
alert('上传文件大小超过'+maxSize+'M');
}else if(type == 'Q_EXCEED_NUM_LIMIT'){
alert('上传文件数量超过'+ limit);
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
$list.append( '<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>' );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo( $li ).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css( 'width', percentage * 100 + '%' );
});
uploader.on( 'uploadSuccess', function( file,response ) {
$( '#'+file.id ).find('p.state').text('已上传');
flashUrl = response.message;
$('.btns').after($('<input type="hidden" value='+flashUrl+' name=game_url>'));
});
uploader.on( 'uploadError', function( file ) {
$( '#'+file.id ).find('p.state').text('上传出错');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').fadeOut();
});
uploader.on( 'all', function( type ) {
if ( type === 'startUpload' ) {
state = 'uploading';
} else if ( type === 'stopUpload' ) {
state = 'paused';
} else if ( type === 'uploadFinished' ) {
state = 'done';
}
if ( state === 'uploading' ) {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
}
});
$btn.on( 'click', function() {
if ( state === 'uploading' ) {
uploader.stop();
} else {
uploader.upload();
}
});
});
var token = $("input[name='__token__']").val();
$(function () {
$("#uploaders").powerWebUpload({ auto: false,fileNumLimit:8,hiddenInputId:token });
});
$(':submit').click(function () {
var inputs = $('.UploadhiddenInput').find('input');
var flashurl = $('input[name="game_url"]');
if(inputs.length == 0){
layer.msg('你必须至少上传一张游戏图片');
return false;
}
if(flashurl.length == 0){
layer.msg('你还没有上传flash游戏呢');
return false;
}
});
</script>
{/block}
控制器代码
<?php
/**
* Created by pan.
* User: pan
* Date: 2017/11/1
* Time: 14:09
* games 游戏 控制器
*/
namespace app\admin\controller;
use app\admin\model\Category;
use app\admin\model\Special;
use app\admin\model\GamesPic;
use app\admin\model\Game;
use think\Controller;
use think\Request;
use think\Db;
class Games extends Base
{
/**
* 显示游戏列表
*
* @return \think\Response
*/
public function index()
{
//gameAll为获取当前游戏列表相关结果集
$list = Game::gameAll();
$this->assign('list',$list);
return $this->fetch();
}
/**
* 添加游戏表单页.
*
* @return \think\Response
*/
public function create()
{
$special = Special::all();
$category = Category::all();
$this->assign('special',$special);
$this->assign('category',$category);
return $this->fetch();
}
/**
* 保存游戏
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
$gamepic = input('post.upfile/a');
// halt($gamepic);
unset($_POST['upfile']);
if($game = Game::create($_POST)) {
$id = $game->id;
$pic = array();
foreach ($gamepic as $index => $item) {
$pic[$index]['game_id'] = $id;
$pic[$index]['pic_url'] = $item;
}
$gamepic = new GamesPic;
if($gamepic->saveAll($pic)) {
$this->success('添加游戏成功','games/index','',1);
}else{
unlink('uploads/games/'.input('post.game_url'));
foreach ($gamepic as $item) {
unlink('uploads/gamespic/'.$item);
}
$this->error('游戏图片存入数据库失败');
}
}else{
unlink('uploads/games/'.input('post.game_url'));
foreach ($gamepic as $item) {
unlink('uploads/gamespic/'.$item);
}
$this->error('游戏失败,请联系管理员');
}
}
/**
* 显示游戏详情
*
* @param int $id
* @return \think\Response
*/
public function read($id)
{
$gid['g.id'] = $id;
$list = Game::gameAll($gid);
if(!$list){
$this->success('游戏不存在','games/index','',1);
}
$this->assign('list',$list);
return $this->fetch();
}
/**
* 显示编辑资源表单页.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
$gid['g.id'] = $id;
$list = Game::gameAll($gid);
if(!$list){
$this->success('游戏不存在','games/index','',1);
}
$special = Special::all();
$category = Category::all();
$this->assign('special',$special);
$this->assign('category',$category);
$this->assign('list',$list);
return view();
}
/**
* 保存更新的资源
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request, $id)
{
//获取post过来的upfile字段集合
$gamepic = input('post.upfile/a');
//删除
unset($_POST['upfile']);
$_POST['id'] = $id;
//获取游戏flash
$gameurl = Game::get($id)->game_url;
//获取传递过来的游戏flash
$flashurl = input('post.game_url');
//如果直接使用模型update方法,返回的是对象.如果采用where->update则返回的是布尔类型
if($game = Game::update($_POST)) {
$id = $game->id;
$pic = array();
//如果传递过来的游戏flash有内容,证明更新了flash文件,所以删除以前的flash文件
if($flashurl) {
if ($gameurl) {
unlink('uploads/games/' . $gameurl);
}
}
//如果更新了游戏轮播图
if($gamepic){
foreach ($gamepic as $index => $item) {
$pic[$index]['game_id'] = $id;
$pic[$index]['pic_url'] = $item;
}
$gamepic = new GamesPic;
if($gamepic->saveAll($pic)) {
$this->success('更新游戏成功','games/index','',1);
}else{
unlink('uploads/games/'.input('post.game_url'));
foreach ($gamepic as $item) {
unlink('uploads/gamespic/'.$item);
}
$this->error('游戏图片存入数据库失败');
}
}else{
$this->success('更新游戏成功','games/index','',1);
}
}else{
if(input('post.game_url')){
unlink('uploads/games/'.input('post.game_url'));
}
if($gamepic){
foreach ($gamepic as $item) {
unlink('uploads/gamespic/'.$item);
}
}
$this->error('更新游戏失败,请联系管理员');
}
}
/**
* 删除指定游戏
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
$gid['g.id'] = $id;
//获取指定游戏id的相关的数据
$list = Game::gameAll($gid);
$str=$list['gcontent'];
//获取百度编辑器内上传的图片
preg_match_all('/<img.*?src="(.*?)".*?>/is',$str,$array);
//如果删除游戏成功
if (Game::destroy($id,true)) {
//如果游戏flash和游戏轮播图都存在,则全部删除
if($list['game_url']) {
unlink('uploads/games/'.$list['game_url']);
}
if($list['picurl']) {
foreach ($list['picurl'] as $item) {
unlink('uploads/gamespic/' . $item['pic_url']);
}
}
//百度编辑器内如果有图片,则全部删除
if($array){
foreach($array[1] as $key=>$value){
$value = trim($value,'/');
unlink($value);
}
}
$this->success('删除游戏成功','games/index','',1);
}else{
$this->error('删除游戏失败');
}
}
/*
* webupload游戏轮播图上传处理
*/
public function upload(Request $request)
{
$file = request()->file('file');
if($file){
//成功移动路到指定路径
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'. DS . 'gamespic');
if($info){
return json([$file,'state'=>'success','message'=>$info->getSavename()]);
}else{
//上传失败获取错误信息
return json(['state'=>'error','message'=>$file->getError()]);
}
}
}
/*
* webupload添加游戏时,对已上传的游戏图片进行ajax删除处理
*/
public function deletefile()
{
$link = input('post.fullName');
unlink('uploads/gamespic/'.$link);
}
//上传游戏flash处理
public function uploadflash()
{
$file = request()->file('flash');
if($file){
//成功移动路到指定路径
$info = $file->validate(['ext'=>'swf'])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS . 'games');
if($info){
//返回json数据给前端js
return json([$file,'state'=>'success','message'=>$info->getSavename()]);
}else{
//上传失败获取错误信息
return json(['state'=>'error','message'=>$file->getError()]);
}
}
}
/*
* 游戏编辑页面,对游戏flash进行ajax删除的处理
*/
public function deleflash($id)
{
$game = Game::get($id);
$url = $game->game_url;
$game->game_url = null;
if($game->save()) {
if (unlink('uploads/games/'.$url)){
return 1;
}
}else{
return 0;
}
}
/*
* 游戏编辑页面,对游戏的图片进行ajax删除处理
*/
public function delepid($pid)
{
$games_pic = db('games_pic');
$piclist = $games_pic->find($pid);
$picurl = $piclist['pic_url'];
if($games_pic->delete($pid)){
if(unlink('uploads/gamespic/'.$picurl)){
return 1;
}
}else{
return 0;
}
}
}