html多文件上传,可支持预览

时间:2022-01-15 11:15:27
 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单提交</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body> <!--文件上传-->
<form id="uploadForm" enctype="multipart/form-data">
<div id="fileId" style='display: none'><!--//style='display: none'--> </div>
<div id="img-con" class="panel panel-default imgdiv"> </div>
<p id="em">未上传文件</p>
<input type="button" value="点击事件" name="点击事件" onclick="inputClieck()"><br>
<input type="submit">
</form>
</body>
<script> var inputArray = []; function inputClieck() {
var newInput = document.createElement("input");
newInput.type = 'file';
newInput.name = "files";
var idid = new Date().getTime();
newInput.id = idid;
$("#fileId").append(newInput);
inputArray.push(idid); $("#" + idid).click(); $("#" + idid).change(function (e) {
console.log('change事件', e);
console.log(this)
var path= getImgPath(this.files[0]);
console.log("--------"+path); var arr = path.split("/");
var strPath='--------:null/'+arr[arr.length-1];
console.log(strPath)
var a=createImg(path,idid);
$("#em").append(a) });
var newline = document.createElement("br");//创建一个BR标签是为能够换行!
$("#fileId").append(newline);
} //动态显示上传图片
function uploadImg(path) {
var imgDiv = $("#img-con");
var $img = $("<img/>");
$img.attr("src", path);
imgDiv.append($img);
} //获取要上传单张图片的本地路径
function getImgPath(file) { var url = null;
if(window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if(window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if(window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
} function createImg(src,idid) {
var box = $("<div class='img-box uploadfile'>"); var newImg = document.createElement("img");
newImg.src=src;
newImg.id="img"+idid;
newImg.height=100;
newImg.width=100;
newImg.onclick='showImagePopup(\"" + src + "\")'; //box.append("<img src='" + src + "' height='100px' width='100px' onclick='showImagePopup(\"" + src + "\")'>");
box.append(newImg);
return box;
} function showImagePopup(src) {
if (getClass(src) === "String") {
var popup = $("<img></img");
popup.addClass("image-popup").attr("src", src);
var shade = $("<div></div>").addClass("shade");
$(document.body).append(shade.append(popup));
shade.click(function () {
$(this).remove();
});
popup.fadeIn(200);
// popup.click(function() {
// window.event ? window.event.cancelBubble = true :
// window.event.stopPropagation();
// });
}
} </script>
</html>