layui图片上传可以一次性选择多个图片,然后选择多少张调用多少次上传接口
设计思路:前端上传文件到后台,后台接收保存成功后返回图片路径,前端根据路径生成div,div包括img标签、隐藏的input(表单传值用)、删除按钮,点击删除按钮判断是第几个删除按钮并删除对应的标签
前端页面:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>多图上传</title>
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
<script src="https://www.layuicdn.com/layui/layui.js"></script>
<style>
.up-img{
width: 100px;
height: 100px;
}
#demo2 div button{
position: relative;
top: -38px;
left: -13px;
}
</style>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传多张图片</legend>
</fieldset>
<div class="layui-upload">
<button type="button" class="layui-btn" id="test2">多图片上传</button>
<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px; height: 142px;">
预览图:
<div class="layui-upload-list" id="demo2" ></div>
</blockquote>
</div>
</body>
<script>
layui.use(['upload','jquery'],function () {
$ = layui.jquery;
var upload = layui.upload;
//执行实例
var uploadInst =
upload.render({
elem: '#test2'
,url: 'upload1.php' //改成您自己的上传接口
,multiple: true
,before: function(obj){
//预读本地文件示例,不支持ie8
// console.log(obj);
obj.preview(function(index, file, result){
// $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img up-img">')
});
}
,done: function(res){
//上传完毕
$('#demo2').append('<div style="float: left;"><img src="'+ res.msg +'" alt="'+ res.msg +'" class="layui-upload-img up-img" onclick="showeq(this)"><input type="hidden" name="image[]" value="'+res.msg+'" onclick="showinput(this)"><button onclick="del(this)">x</button></div>');
// $('#demo2').append('');
// $('#demo2').append('');
}
});
});
function showeq(params) {
var index = $("#demo2 img").index(params);
console.log(index);
}
function showinput(params) {
var index = $("#demo2 input").index(params);
console.log(index);
}
function del(params) {
var index = $("#demo2 button").index(params);
$("#demo2 button").eq(index).remove();
$("#demo2 input").eq(index).remove();
$("#demo2 img").eq(index).remove();
// console.log(index);
}
</script>
</html>
php代码
<?php
$file = $_FILES["file"];
if ($file==null) {
exit(json_encode(array('code'=>1, 'msg'=>'未上传图片')));
}
// 获取文件后缀
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
// 判断文件是否合法
if(!in_array($extension, array("gif","jpeg","jpg","png"))){
exit(json_encode(array('code'=>1, 'msg'=>'上传图片不合法')));
}
$info = move_uploaded_file($file['tmp_name'], "./uploads/".$file['name']); //移动文件到指定目录 建议文件名自己在修改一下
$img = '/uploads/'.$file['name'];
exit(json_encode(array('code'=>0, 'msg'=>$img)));
?>
评论 (0)