html
js
$(function() {
var $gallery = $("#gallery"),
$galleryImg = $("#galleryImg"),
$uploaderFiles = $("#uploaderFiles");
// 允许上传的图片类型
var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
// 1024KB,也就是 1MB
var maxSize = 1024 * 1024;
// 图片最大宽度
var maxWidth = 300;
// 最大上传图片数量
var maxCount = 6;
$('.js_file').on('change', function (event) {
var files = event.target.files;
// 如果没有选中文件,直接返回
if (files.length === 0) {
return;
}
for (var i = 0, len = files.length; i < len; i++) {
var file = files[i];
var reader = new FileReader();
// 如果类型不在允许的类型范围内
if (allowTypes.indexOf(file.type) === -1) {
$.weui.alert({text: '该类型不允许上传'});
continue;
}
if (file.size > maxSize) {
$.weui.alert({text: '图片太大,不允许上传'});
continue;
}
if ($('.weui_uploader_file').length >= maxCount) {
// $.weui.alert({text: '最多只能上传' + maxCount + '张图片'});
layui.use('layer', function(){
var layer = layui.layer;
layer.msg('最多只能上传' + maxCount + '张图片');
});
return;
}
reader.onload = function (e) {
var img = new Image();
img.onload = function () {
// 不要超出最大宽度
var w = Math.min(maxWidth, img.width);
// 高度按比例计算
var h = img.height * (w / img.width);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 设置 canvas 的宽度和高度
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
var base64 = canvas.toDataURL('image/png');
// 插入到预览区
var $preview = $('0% ');
$('.weui_uploader_files').append($preview);
var num = $('.weui_uploader_file').length;
$('.js_counter').text(num + '/' + maxCount);
// 然后假装在上传,可以post base64格式,也可以构造blob对象上传,也可以用微信JSSDK上传
var progress = 0;
function uploading() {
$preview.find('.weui_uploader_status_content').text(++progress + '%');
if (progress < 100) {
setTimeout(uploading, 30);
}
else {
// 如果是失败,塞一个失败图标
//$preview.find('.weui_uploader_status_content').html('');
$preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
}
}
setTimeout(uploading, 30);
};
img.src = e.target.result;
$.post("{:U('pyq/upload')}", { img: e.target.result},function(res){
if(res.img!=''){
// alert('upload success');
$('#image-all').val($('#image-all').val() + res.img + ',');
}else{
alert('upload fail');
}
},'json');
};
reader.readAsDataURL(file);
}
});
$uploaderFiles.on("click", "li", function() {
$galleryImg.attr("style", this.getAttribute("style"));
$gallery.fadeIn(100);
});
$gallery.on("click", function() {
$gallery.fadeOut(100);
});
//删除图片
var index; //第几张图片
$uploaderFiles.on("click", "li", function() {
index = $(this).index();
$galleryImg.attr("style", this.getAttribute("style"));
$gallery.fadeIn(100);
});
$gallery.on("click", function() {
$gallery.fadeOut(100);
});
$(".weui-gallery__del").click(function() {
//删除image-all中的值,index表示点击的第几张,同比删除
var imageall = $('#image-all').val().split(',');
//删除第index项,newimageall为删除的那一项,'["/Public/upload/test/201902/1549878149.jpg"]'
var newimageall = imageall.splice(index, 1);
//我们用ajax把后台中的文件删除掉。
$.post("{:U('pyq/delupload')}", { img: newimageall[0]}, function(res){
//如果status为2说明删除失败,这里在控制台输出一下,方便后期排查
if(res['status'] == '2'){
console.log('删除失败!');
}else{
var num = $('.weui_uploader_file').length;
$('.js_counter').text(num + '/' + maxCount);
}
},'json');
//把 imageall 数组用 ‘,’ 拼装起来
var image_all_str = imageall.join(',');
//重新设置 image-all中的值
$('#image-all').val(image_all_str);
//删除预览项
$('#uploaderFiles li').eq(index).remove();
$('.weui-uploader__input-box').show();
});
//提交
$('#btnsaveCharge').click(function() {
var duotu = $('#image-all').val();
var content = $('#pyq_content').val();
//如果多图为空,且内容为空,则不允许提交
if( $('#pyq_content').val() == '' && $('#image-all').val() == ''){
layui.use('layer', function(){
var layer = layui.layer;
layer.msg('请填写内容或者添加图片!');
});
return false;
}
var data = {duotu: duotu, content: content};
var url = "{:U('pyq/zadd')}";
$.post(url, data, function(result) {
new_result = $.parseJSON(result);
if (new_result.status == 0) {
layui.use('layer', function(){
var layer = layui.layer;
layer.msg(new_result.message);
});
}
if (new_result.status == 1) {
layui.use('layer', function(){
var layer = layui.layer;
layer.msg(new_result.message, { icon: 1, time: 1000 }, function() {
window.location.href = "{:U('pyq/index')}";
});
});
}
});
})
});
php
public function upload()
{
if (!empty($_POST)) {
$img = isset($_POST['img']) ? $_POST['img'] : '';
// 获取图片
list($type, $data) = explode(',', $img);
// 判断类型
if (strstr($type, 'image/jpeg') != '') {
$ext = '.jpg';
} elseif (strstr($type, 'image/gif') != '') {
$ext = '.gif';
} elseif (strstr($type, 'image/png') != '') {
$ext = '.png';
}
//保存路径设置
$conf = array(
'rootPath' => './Public/upload/',
'savePath' => 'test/',
'subName' => date('Ym'),
);
$path = $conf['rootPath'] . $conf['savePath'] . $conf['subName'] . '/';
//如果路径文件夹不存在,就建立文件夹
if (!is_dir($path)) {
$flag = mkdir($path, 0777, true);
}
//文件名通过这种方式达到不一致,不然一次性选择多张图片,只会显示最后一张
$imgfont = time() + rand(1, 10000);
// 生成的文件名
$photo = $path . $imgfont . $ext;
// 生成文件
file_put_contents($photo, base64_decode($data));
//原图很大,制作小图然后删除原图
$im = new \Think\Image();
// $photo == ./Public/upload/test/201902/1549936204.jpg
//打开全图
$im->open($photo);
//为原图制作 小图
$im->thumb(1000, 1000);
//保存
$smallpic = $path . 'sm_' . $imgfont . $ext;
$sm = $im->save($smallpic);
//删除原图
unlink($photo);
//将$photo前面的'.'去掉
$smallpic = ltrim($smallpic, '.');
// 返回
header('content-type:application/json;charset=utf-8');
$res = array('img' => $smallpic);
echo json_encode($res);
} else {
$this->display();
}
}
//删除已经上传的文件
public function delupload()
{
if (!empty($_POST)) {
$img = isset($_POST['img']) ? $_POST['img'] : '';
//删除已经上传的文件
$flag = unlink('.' . $img);
if ($flag) {
return show(1, '删除成功!');
} else {
return show(2, '删除失败!');
}
}
}