1,首先下载百度插件webupload
2,创建控制器UploadsController.class.php,创建与控制器相对应的视图Upload文件夹,文件夹有add.html文件
3,将下载的webupload文件放在根目录Public文件夹下,在add.html中导入其中两个文件,全部代码如下(其中include的头部和尾部文件都是根据H-ui而建立的公共文件,用过H-ui的都知道不了解的去自行了解 ):
<include file="Public/header"/>
<link href="__PUBLIC_ADMIN__/lib/webuploader/0.1.5/webuploader.css" rel="stylesheet" type="text/css" />
<article class="page-container">
<form class="form form-horizontal" id="form">
<input type="hidden" name="id" value="{$data.id}">
<div class="row cl">
<label class="form-label col-xs-2 col-sm-2">
<span class="c-red">*</span> 图片:</label>
<div class="formControls col-xs-9 col-sm-9">
<input type="hidden" name="img" id="img" value="{$data.img}">
<?php if(cookie('img')){?>
<div id="uploadimg" onClick=''>
<div id="fileList" class="uploader-list"></div>
<div id="imgPicker">选择图片</div>
</div>
<?php }?>
</div>
</div>
<div class="row cl">
<div class="col-xs-9 col-sm-9 col-xs-offset-2 col-sm-offset-2">
<button onClick="save()" class="btn btn-secondary radius" type="button"> 提 交</button>
</div>
</div>
</form>
<!-- <div class="row cl">
<div class="col-xs-9 col-sm-9 col-xs-offset-2 col-sm-offset-2">
<button onClick="save()" class="btn btn-secondary radius" type="button"> 提 交</button>
</div>
</div> -->
<!-- </form> -->
</div>
<!-- 公共js文件 -->
<include file="Public/js" />
<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="__PUBLIC_ADMIN__/lib/webuploader/0.1.5/webuploader.min.js"></script>
<!-- 上传文件代码块start -->
<script>
//首先创建WebUploader实例:
var uploader = WebUploader.create({
auto: true, // 选完文件后,是否自动上传
swf: '__PUBLIC_ADMIN__/lib/webuploader/0.1.5/Uploader.swf', // swf文件路径
server: '{:U("fileUpload")}', // 文件接收服务端
pick: '#imgPicker', // 选择文件的按钮。可选
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image',
}
});
//接着监听fileQueued事件,即当有文件添加进来的时候,通过uploader.makeThumb来创建图片预览图。
uploader.on( 'fileQueued', function( file ) {
var $list = $("#fileList"),
//显示文件名
//'<div class="info">' + file.name + '</div>'
$li = $(
'<div id="' + file.id + '" class="file-item thumbnail">' +
'<img>' +
'<div class="info">' +"点击可删除图片"+ '</div>' +
'</div>'
),
$img = $li.find('img');
// $list为容器jQuery实例
$list.append( $li );
// 创建缩略图
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$img.replaceWith('<span>不能预览</span>');
return;
}
$img.attr( 'src', src );
}, 200, 200 ); //100x100为缩略图尺寸
});
//最后是上传状态提示了,当文件上传过程中, 上传成功,上传失败,上传完成都分别对应uploadProgress, uploadSuccess, uploadError, uploadComplete事件。
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress span');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo( $li )
.find('span');
}
$percent.css( 'width', percentage * 100 + '%' );
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file, res ) {
console.log(res.filePath);//这里可以得到上传后的文件路径
$( '#'+file.id ).addClass('upload-state-done');
$('#imgPicker').css('display','none');
$('#uploadimg').attr('onClick','delUpload()');
$('#img').attr('value',$.cookie('img'));
});
// 文件上传失败,显示上传出错。
uploader.on( 'uploadError', function( file ) {
var $li = $( '#'+file.id ),
$error = $li.find('div.error');
// 避免重复创建
if ( !$error.length ) {
$error = $('<div class="error"></div>').appendTo( $li );
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').remove();
});
function delUpload(){
layer.confirm('要删除这张图片吗?',function(index){
layer.msg('删除图片中...', {icon: 16,time:2000});
$.ajax({
url: '{:U("delFileUpload")}',
dataType: 'json',
success:function(result){
if(result!='OK'){
layer.alert(result, {icon: 2,title :'错误提示'});
}
},
error:function(data) {
console.log(data.msg);
},
});
// $('.img_hidden').css('display','none');
$('#img').attr('value',' ');
$('.thumbnail').remove();
$('#uploadimg').attr('onClick','');
$('#imgPicker').css('display','block');
layer.close(index);
}
);
}
</script>
<!-- 上传文件代码块end -->
<script>
var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
//提交
function save(){
var id = parseInt($('input[name="id"]').val());//获取id,以改变操作反馈提示
var admin_title;
if (id>0) { admin_title = '编辑'; }
else{ admin_title = '添加'; }
layer.msg('正在'+admin_title+'...', {icon: 16});
$.ajax({
type:'post',
url:"{:U('save1')}",
data:$("#form").serialize(),
dataType:'json',
success:function(result){
if(result=='OK'){
parent.layer.msg('单图片上传'+admin_title+'成功',{icon:1,time:1000});
parent.setTimeout("location.reload()",1000);
parent.layer.close(index);
}else{
layer.alert(result, {icon: 2,title :'错误提示'});
}
}
});
return false;
}
</script>
</body>
</html>
后台代码如下:
<?php
namespace Admin\Controller;
/*
*CommonController是防止用户非法登录,没有做则改为Controller,
*同时namespace Admin\Controller;改为namespace Admin\Controller;
use Think\Controller;
*/
class UploadsController extends CommonController {
public function oneImg(){
$data = M('uploads')->where("file = ''")->select();
$title = '单图片上传';
$this->assign('title',$title);
$this->assign('data',$data);
$this->display();
}
/**
* 添加或者编辑单图片
*/
public function add1(){
$id = I('id','','intval');
if($id>0){
$title = '编辑单图片上传';
$data = M('uploads')->find($id);
$this->assign('data',$data);
}
else{
$title = '添加单图片上传';
}
$this->assign('title',$title);
$this->display();exit();
}
public function save1(){
$id = (int)I('post.id');
$m = M('Uploads');
$data['img'] = I('img','','trim');
if(!$data['img']){
$this->ajaxReturn('请上传图片');
}
//数据入库
if($id == 0){
$data['add_time'] = time();
$res = $m->add($data);
if(!$res){
$this->ajaxReturn('新增失败');
}
$this->ajaxReturn('OK');
}else{
$res = $m->where('id='.$id)->save($data);
if(!$res){
$this->ajaxReturn('修改失败');
}
$this->ajaxReturn('OK');
}
}
//tp上传图片到本地
public function fileUpload(){
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './Uploads/'; // 设置附件上传根目录
$upload->savePath = ''; // 设置附件上传(子)目录
// 上传文件
$info = $upload->upload();
if(!$info) {
// 上传错误提示错误信息
$this->error($upload->getError());
}else{
// 上传成功 获取上传文件信息
foreach($info as $file){
$imginfo = "/Uploads/".$file['savepath'].$file['savename'];
cookie('img',$imginfo);
// echo $imginfo;
}
}
}
//删除服务器里单个文件方法
public function delFileUpload(){
// $filename = ROOT_PATH . 'public' . DS . 'uploads/20180628/1.jpg';
// $filename = ROOT_PATH . '/Uploads
// /2019-06-18/5d081cc528d4f.jpg';
$path=ROOT_PATH.'/Uploads
/'.date("Y-m-d");
if(file_exists($path)){
$handle = opendir($path);
while (false !==$file = readdir($handle)){
if ($file !='.' && $file != '..'){
$file_fullpath = $path."/".$file;
echo iconv('GBK', 'utf-8', $file_fullpath);
echo "<br />";
if (!is_dir($file_fullpath)){
unlink($file_fullpath);
}else{
rmdir($file_fullpath);
}
}
}
}
if(file_exists($filename)){
unlink($filename);
$this->ajaxReturn('删除失败');
}else{
$this->ajaxReturn('OK');
// return '我已经被删除了哦!';
}
}
}
以上单图片上传完毕,发现webupload还是有不小的缺陷,就是本地上传图片,你把该图片删除后就不能再上传改图片,我想是因为webupload为了防止用户重复提交而设置的功能,而解决此bug的方法有两个思路,深入研究webupload修改防止重复提交相同图片的代码,第二个是七牛云上传图片,然后七牛云删除图片。