手机H5网站上传图片是基本的一个功能,所以一般程序都会用到。思路基本如下
1.图片选择
2.图片缩略展示
3.图片详情展示
4.图片删除
5.图片上传
1.图片选择
html标签代码
上传图片(最多可上传9张)
![](/img/mobile/icon_add.png)
图片展示的时候必须要将手机端的图片旋转角度,不然上传的图片就是90度的图片会影响图片的浏览
使用插件JavaScript-Load-Image可以将图片旋转和压缩大小
$(document).on("click",".btn_add",function () {
$('#input').trigger('click')
});
$(document).on("change","#input",function () {
var input = $(this)[0]; // input 控件
imagesChanged(input);
});
/**
* 添加图片回调
*/
function imagesChanged(input) {
var files = input.files;
// 假设 "listView" 是将要展示图片的 div
var listView = $("#listView");
for (var i = 0; i < files.length; i++) { //新添加的图片
var file = files[i];
imgFiles.push(file);
// Make sure `file.name` matches our extensions criteria
if ( !/\.(jpe?g|png|gif)$/i.test(file.name) ) {
continue;
}
var options = {
orientation: true,
maxWidth: 640,
}
loadImage(
file,
function (img) {
var base = img.toDataURL("image/jpeg");
var imgRow = getImageRow(base);
imgData.push(base);
// add_doc(base);
listView.append(imgRow);
},
options // Options
);
//最多张数
if (imgFiles.length >= imgCountMax) {
$("#inputDiv").hide();
break;
}
}
}
// 插入一行图片
function getImageRow(imgSrc) {
// 向 listView 添加一行 row
var imgRow =
'' +
'![](/img/mobile/icon_del.png)'+
'![](' + imgSrc + ')' +
'';
return imgRow;
}
2.缩略展示已经在上中
3.详情图片展示
主要使用了插件photoswipe友好的展示了图片的详情
$(document).on("click",".weui_uploader_file",function () {
var indexSel = $('.weui_uploader_file').index(this);
var imgArr = $('.weui_uploader_file');
var items = new Array();
imgArr.each(function (i) {
var img = imgArr[i];
var item = new Object();
item.src = img.src;
item.w = img.naturalWidth;
item.h = img.naturalHeight;
items.push(item);
});
var pswpElement = document.querySelectorAll('.pswp')[0];
var options = {
index: indexSel,
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
});
4.删除图片
这个最简单删除临时的图片存储数据,删除展示div即可
$(document).on("click",".btn_close",function(){
indexSel = $('.btn_close').index(this);
imgFiles.splice(indexSel,1);
imgData.splice(indexSel,1);
// $('.update_img')[indexSel].remove();
$('.cell_img')[indexSel].remove();
if (imgFiles.length >= imgCountMax) {
$("#inputDiv").hide();
}else{
$("#inputDiv").show();
}
})
5.图片上传
我是用laravel框架的所以要设置CSRF令牌,因为是图片上传所以会有点慢,那就需要一个友好的交互等待界面
使用iosOverlay,简单易用
$(document).on("click",".btn_primary",function () {
var title = $('#title').val();
var mood = $('#mood').val();
if (!title) {
alert("标题不能为空");
return;
}
if (!mood) {
alert("心情不能为空");
return;
}
if (!imgData) {
alert("图片不能为空");
return;
}
var overlay = iosOverlay({
text: "Loading",
duration: 20e3,
icon: "/packages/common/iosOverlay/img/load.gif"
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/ssp_updata",
data: {"title": title, "mood": mood, "imgData": imgData},
dataType: 'json',
success: function (data) {
if (data.success) {
overlay.update({
icon: "/packages/common/iosOverlay/img/check.png",
text: data.msg
});
window.location.href = "/ssp";
} else {
overlay.update({
icon: "/packages/common/iosOverlay/img/cross.png",
text: data.msg
});
}
},
error: function (xhr, type) {
overlay.update({
icon: "/packages/common/iosOverlay/img/cross.png",
text: "服务器连接错误"
});
}
});
});
6.最后一步服务器端接收图片
注意本人使用的是Laravel所以是这样的的写法,用TP的就要自己写了
只需要注意传回的canvas流需要去除前面描述字段·base64_decode(substr($value, 23))·
jpg的是23个字段,png是22个字段
public function ssp_updata(Request $request){
$data = $request->all();
$rules = [
'title' => 'required',
'mood' => 'required',
'imgData' => 'required'
];
$messages = [
'title.required' => '标题必须填写',
'mood.required' => '心情必须填写',
'imgData.required' => '图片必须大于1张'
];
$validator = Validator($data, $rules, $messages);
if ($validator->passes()) {
$imgPath = [];
$imgArr = $data['imgData'];
$storage = Storage::disk(config('admin.upload.disk'));
$directory = '/image/'.date('Y', time()).'/'.date('md', time())."/";
$name = time();
foreach ($imgArr as $key => $value){
$target = $directory.$name.$key.".jpg";
$storage->put($target, base64_decode(substr($value, 23)));
$imgPath[$key] = $target;
}
$user = session('user');
$Snap = new Snapshots();
$Snap->title = $data['title'];
$Snap->mood = $data['mood'];
$Snap->files = json_encode($imgPath);
$Snap->users_id = $user->id;
$Snap->save();
$res = ['success'=>true,'msg'=>"提交成功"];
return $res;
} else {
$res = ['success'=>false,'msg'=>$validator->messages()->first()];
return $res;
}
}