<style>
.file {
border: 1px solid rgba(0, 0, 0, 0.22);
position: relative;
display: inline-block;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent: 0;
line-height: 20px;
width: 16%;
height: 220px;
background: url(/img/default.png);
background-size: 100% 100%;
background-position: center center;
}
.file input {
cursor: pointer;
border-color: #78C3F3;
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
}
.file:hover {
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
</style>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js上传图片并展示</title>
</head>
<body>
<a href="javascript:;" class="file">
<input type="hidden" name="mec_share_img" value="" class="mec_img">
<input type="file" name="share_img" class="img" kb_max="1024" data-format="image/gif,image/jpeg,image/png,image/jpg,image/bmp">
</a>
</body>
</html>
<script src="/js/jquery.min.js"></script>
<script src="/layui/layui.all.js"></script>
<script>
$(".img").change(function () {
var reads = new FileReader();
var f = $(this).get(0).files[0];
var filesize = f.size;
var maxsize = $(this).attr('kb_max');//1M
var kb_max = maxsize + 'K';
if(maxsize >= 1024){
kb_max = maxsize / 1024 + 'M';
}
if ((filesize/1024) > maxsize) {
layer.msg('请上传小于'+kb_max+'的图片!');return ;
}
reads.readAsDataURL(f);
var that = this;
reads.onload = function (e) {
var _this = this
var data = e.target.result;
//加载图片获取图片真实宽度和高度
var image = new Image();
image.src = data;
// 图片先加载完,才可以得到图片宽度和高度
image.onload = function () {
$(that).parents('.file').css("background","url("+ _this.result+")")
$(that).parents('.file').css("background-size","100% 100%")
$(that).parents('.file').css(" background-position","center center")
}
};
// var formData = new FormData();
// formData.append("upload_file",f);
// var url = '/system/ajax/ajax_upload_image';
// $.ajax({
// url:url, /*接口域名地址*/
// type:'post',
// data: formData,
// contentType: false,
// processData: false,
// success:function(res){
// $(that).parents('.file').find('.mec_img').val(res.data.save_name)
// }
// })
})
</script>```
![url图片](https://img-blog.csdnimg.cn/20210117133606715.png#pic_center)
js上传图片并展示
最新推荐文章于 2024-04-17 16:35:15 发布