实现多图片上传,拖拽,拖动改变循序,删除,预览。
<style>
.gallery {
display: flex;
flex-direction: row;
flex-wrap: wrap;
padding: 20px;
0 0 10px;
}
.gallery .img-item {
position: relative;
cursor: pointer;
margin-bottom: 10px;
}
.gallery .img-item .delete {
position: absolute;
display: block;
width: 20px;
height: 20px;
color: #fff;
background: rgba(232, 0, 0, 0.7);
line-height: 20px;
text-align: center;
border-radius: 50%;
top: -10px;
right: -10px;
cursor: pointer;
}
.box {
width: 100%;
height: 100%;
position: fixed;
top: 0px;
left: 0px;
right: 0px;
bottom: 0;
margin: 0 auto;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
display: none;
overflow: hidden;
}
.box img {
width: 50%;
position: absolute;
}
.btn-upload {
margin: 20px;
float: left;
display: block;
width: 100px;
height: 100px;
border: 1px solid #ddd;
background: #ebebeb;
line-height: 100px;
font-size: 14px;
text-align: center;
color: #808080;
cursor: pointer;
}
.img {
width: 100px;
height: 100px;
margin-left: 10px;
cursor: pointer;
}
</style>
<form id="formdata">
<div class="gallery" id="gallery">
<div class="img-item" style="display: inline-block;margin-left:10px;order:999" id="first-btn-upload">
<label for="btn-upload" class="btn-upload iconfont" style="margin:0px;font-size:36px;" id="btn-upload"></label>
</div>
</div>
<input id="file" type="file" multiple accept="image/*" style="display: none">
<div class="box">
<div style="width:100%;height:100%;opacity:0.6;background:#000000"></div>
<img class="" src="" />
</div>
<button οnclick="Up()">上传</button>
</form>
function Up() {
//根据图片的数量循环执行保存图片
for (var i = 0; i < files.length; i++) {
var uploaddata = new FormData($("#formdata")[0]);
// 遍历图片数组把图片添加到FormData中
///返回的图片路径保存到数组当中
uploaddata.append("file", files[i]);
console.log(uploaddata);
$.ajax({
type: "post",
url: "/Demo/UploadImg/Upload",
data: uploaddata,
contentType: false, // 注意这里应设为false
processData: false, //false
cache: false, //缓存
success: function (data) {
console.log(data);
}
})
return false;
}
}
//
$('#lr_refresh').on('click', function () {
location.reload();
});
</script>
<script>
var num = 0;
// 预览
function preView(obj) {
var pimg = obj;
// var pimg = document.querySelector("img");
var oImg = document.querySelector(".box img");
var oBox = document.querySelector(".box");
// pimg.οnclick=function(){
oBox.style.display = "flex"
oImg.src = pimg.src
// }
oBox.onclick = function () {
oBox.style.display = "none"
oImg.src = ''
}
var hammer = new Hammer(oImg);//hammer实例化
hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });//激活pan(移动)功能
hammer.get('pinch').set({ enable: true });//激活pinch(双指缩放)功能
hammer.on("panstart", function (event) {
var left = oImg.offsetLeft;
var tp = oImg.offsetTop;
hammer.on("panmove", function (event) {
oImg.style.left = left + event.deltaX + 'px';
oImg.style.top = tp + event.deltaY + 'px';
});
})
hammer.on("pinchstart", function (e) {
hammer.on("pinchout", function (e) {
oImg.style.transition = "-webkit-transform 300ms ease-out";
oImg.style.webkitTransform = "scale(2.5)";
});
hammer.on("pinchin", function (e) {
oImg.style.transition = "-webkit-transform 300ms ease-out";
oImg.style.webkitTransform = "scale(1)";
});
})
}
// 创建数组保存图片
var files = new Array();
var id = 0;
// 选择图片按钮隐藏input[file]
$("#btn-upload").click(function () {
$("#file").trigger("click");
});
// 选择图片
$("#file").change(function (e) {
console.log(e);
console.log('点击确定执行了这个方法');
// 获取所有图片
var img = document.getElementById("file").files;
// 遍历
for (var i = 0; i < img.length; i++) {
// 得到图片
var file = img[i];
// 判断是否是图片
var flag = judgeImgSuffix(file.name);
if (flag) {
} else {
alert("要求图片格式为png,jpg,jpeg,bmp");
return;
}
// 把图片存到数组中
files[id] = file;
console.log(files[id]);
id++;
// 获取图片路径
var url = URL.createObjectURL(file);
// 创建img
var box = document.createElement("img");
box.setAttribute("src", url);
box.className = 'img';
box.draggable = true;
box.id = "img" + num;
box.onclick = function () {
preView(this);
};
// 创建div
var imgBox = document.createElement("div");
imgBox.style.float = 'left';
imgBox.className = 'img-item';
imgBox.id = 'div' + num;
num++;
// 创建span
var deleteIcon = document.createElement("span");
deleteIcon.className = 'delete';
deleteIcon.innerText = 'x';
// 把图片名绑定到data里面
deleteIcon.id = img[i].name;
// 把img和span加入到div中
imgBox.appendChild(deleteIcon);
imgBox.appendChild(box);
// 获取id=gallery的div
var body = document.getElementsByClassName("gallery")[0];
body.appendChild(imgBox); //在末尾处添加图片 下面方式在开头添加图片
//var showPlace = document.getElementsByClassName("img-item")[0];
//body.insertBefore(imgBox,showPlace);
// 点击span事件
$(deleteIcon).click(function () {
// 获取data中的图片名
var filename = $(this).attr('id');
// 删除父节点
$(this).parent().remove();
var fileList = Array.from(files);
// 遍历数组
for (var j = 0; j < fileList.length; j++) {
// 通过图片名判断图片在数组中的位置然后删除
if (fileList[j].name == filename) {
fileList.splice(j, 1);
id--;
break;
}
}
files = fileList;
});
}
document.getElementById('file').value = null;
});
// 判断是否是图片类型
function judgeImgSuffix(path) {
var index = path.lastIndexOf('.');
var suffix = "";
if (index > 0) {
suffix = path.substring(index + 1);
}
if ("png" == suffix || "jpg" == suffix || "jpeg" == suffix || "bmp" == suffix || "PNG" == suffix || "JPG" == suffix || "JPEG" == suffix || "BMP" == suffix) {
return true;
} else {
return false;
}
}
</script>
<script>
const dragCon = document.getElementById('gallery');
dragCon.addEventListener('dragstart', startDrag, false);
/**
* 这里一定要阻止dragover的默认行为,不然触发不了drop
*/
dragCon.addEventListener('dragover', function (e) {
e.preventDefault();
}, false);
dragCon.addEventListener('drop', exchangeElement, false);
function startDrag(e) {
console.log(e)
e.dataTransfer.setData('Text', e.target.id + ';' + e.target.parentElement.id);
}
function exchangeElement(e) {
e.preventDefault();
const el = e.target;
let PE, //要插入位置的父元素
CE; //需要交换的元素
if (el.tagName.toLowerCase() !== 'div') {
PE = el.parentElement;
CE = el;
} else {
PE = el;
CE = el.querySelector('img');
}
/**
* 判断不在控制范围内
*/
if (!PE.classList.contains('img-item')) {
return;
}
const data = e.dataTransfer.getData('Text').split(';');
//交换元素
document.getElementById(data[1]).appendChild(CE);
PE.appendChild(document.getElementById(data[0]));
}
</script>
后端代码
/// <summary>
/// 上传
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Upload()
{
int num = Request.Files.Count;
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0)
{
string title = string.Empty;
title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);
string path = "../UploadFile/" + title;
path = System.Web.HttpContext.Current.Server.MapPath(path);
file.SaveAs(path);
return Json(new { status = true, url = path });
}
else
{
return Json(new { status = false, url = "上传失败" });
}
}
``