對百度上傳webupload外掛的兩種寫法
阿新 • • 發佈:2019-02-05
第一種呼叫一個封裝好的js
使用方法:
呼叫mywebupload.js
js例項化
$(function () {
$("#uploaders").powerWebUpload({ auto: false,fileNumLimit:8,hiddenInputId:token });
});
要修改引數等內容,去修改mywebupload.js檔案
可以實現圖片批量,指定數量,大小,上傳發表前刪除,等等功能
參考資料:
(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;
}
}
}