分享一个传多图片的方法之base64
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>图片转化成base64-API上传</title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
<style>
.imgList img {
padding: 20px;
width: 200px;
height: 200px;
}
.imgBase64 textarea {
padding: 20px;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div style="width: 100%;">
<div class="imgshow" style="width: 80%;margin: 0 auto;">
<h2>这里是上传的图片显示:</h2>
<div class="imgList" style="min-height: 200px;border: 1px solid red;margin-top: 50px;">
</div>
</div>
<div style="width: 80%;margin: 50px auto;">
<label for="fileupload" style="cursor: pointer;display: block; text-align: center;line-height: 50px;color: #fff; width: 200px;height: 50px;border-radius: 6px;background: pink;">点击选择文件</label>
<div class="copyinput"><input type="file" id="fileupload" name="wq" style="display: none;"></div>
</div>
<div class="imgshow" style="width: 80%;margin: 0 auto;">
<h2>这里是显示上传图片的base64:</h2>
<div class="imgBase64" style="min-height: 200px;border: 1px solid red;margin-top: 50px;">
</div>
</div>
<!-- <form action="./index1.php" method="post" enctype="multipart/form-data">
<input type="submit" value="提交">
</form> -->
</div>
<script>
//声明一个保存base64的数组
var file_base64 = [];
//l声明一个临时变量
var temp;
//允许图片上传的大小 单位为M
var Maxsize = 2;
$("#fileupload").change("click",function() {
//上传图片
var file = this.files[0];
console.log(file)
// 限制图片大于2兆
if(file.size/1024/1024 > Maxsize ) {
alert('最大支持2M的图片');
return false;
}
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if(!/image\/\w+/.test(file.type)){
alert('请确保文件为图像类型');
$("#fileupload").val('');
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
temp = this.result;
file_base64.push(temp);
$(".imgBase64").append('<div style="display: inline-block;"><p style="padding-left:20px;">' + file.name + '</p><textarea name="" id="" cols="30" rows="10">'+ file_base64[0] +'</textarea></div>')
}
var objUrl = getObjectURL(this.files[0]) ;
if (objUrl) {
$("div.imgList").append('<img src="' + objUrl + '" alt="" />');
}
});
function getObjectURL(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;
}
//API发送 selector yourself selector
$("selector").click(function(event) {
$.post('your url ',{imgbase64 : file_base64},function(data) {
// some code return your
});
});
</script>
</body>
</html>