一、示例简图
二、主要技术栈
- bootstrap
- ajax
- FileAPI
三、主要代码
<body>
<div class="panel panel-info" style="width:50%;margin: 200px auto;">
<div class="panel-heading">FileApI-Demo</div>
<div class="panel-body" style="min-height: 227px;">
<label class="label label-primary sel-img"><input type="file" class="hide" multiple id="select-file"
accept="image/png,image/jpg,image/jpeg">选择图片</label>
<div id="image-list">
</div>
</div>
<div class="panel-footer">
<button class="btn btn-primary btn-sm upload">上传图片</button>
</div>
</div>
<script>
$(function () {
var imgData = []
// 获取图片
$("#select-file").on('change', function (e) {
var files = this.files
for (let i = 0; item = files[i]; i++) {
var reader = new FileReader()
reader.onload = (function (item) {
return function (e) {
var imgId = new Date().getTime()
imgData.push({
id: imgId,
name: item.name,
url: e.target.result,
size: item.size
})
$("#image-list").append(
'<div class="img-box"><img width = "100%" class="selected-img" id="' + imgId +
'" src = "' + e.target
.result + '" alt = "' + item.name +
'" /><button class = "btn btn-xs remove"> X </button></div>')
}
})(item)
reader.readAsDataURL(item) //以url的形式读出图片
}
})
//删除选择的图片
$("#image-list").on('click', '.remove', function () {
$(this).parent().remove()
var oId = parseInt($(this).prev(".selected-img").attr("id"))
imgData = imgData.filter(function (img) {
return img.id !== oId
})
})
// 上传图片
$(".upload").on('click', () => {
if (imgData.length > 0) {
$.ajax('/upload.php', {
method: 'POST',
data: JSON.stringify(imgData),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function () {
alert("Upload image success");
},
error: function () {
alert("Upload image error");
}
})
} else {
alert("please choose a image for upload")
}
})
})
</script>
</body>
注:关于FileAPI更多的内容,可以参考我的另外一篇文章---->HTML5中的文件读取---File API