html5前端上传图片预览删除小实例 js图片base64预览操作

这篇文章发布于

DeathGhost 编辑, 归类于 javascript » 当前评论 0 条。

在项目操作中,时常会用到图片上传功能,例如:上传头像,上传封面照片或产品图片等。我们可以借助Web App中得FileReader接口对其读取进行相应操作。

上传文件时,我们会选择input:file标签类型,当input:file事件change获取文件时,我们就可以利用FileReader读取文件信息,相关得接口大家可以网上查询,这里只是做个个人笔记。

首先进行html结构布局,根据设计需求或个人意愿进行设计,下面是一个小小Demo,仅供参考。

ps:熟悉的宝贝们可以直接跳过,这个是我新创建的站点,以前内容都清空了,现在重新编写,想起什么做到什么不熟悉的给自己做个笔记巩固一下。

涉及到关注点:

  1. input html5新属性(accept 属性只能与 <input type="file"> 配合使用。它规定能够通过文件上传进行提交的文件类型。)
  2. FileReader 对象(对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。)
  3. css3相关

样式:

.uploadGroup{
    position:relative;
    margin:10px 0;
    width:100px;
    height:100px;
    line-height:100px;
    border:1px rgba(0,0,0,.5) solid;
    margin-right:10px;
    border-radius:3px;
    text-align:center;
    overflow:hidden;
}
.uploadGroup label{
    display:block;
    width:100%;
    height:100%;
    z-index:0;
}
.uploadGroup label:last-of-type{margin-right:0;}
.uploadGroup .uploadIco{font-size:2em;}
.uploadGroup img{
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%, -50%);
    width:auto;
    max-width:100%;
    height:auto;
}
.uploadGroup .closeBtn{position:absolute;right:5px;top:5px;line-height:normal;z-index:1;cursor:pointer;}

布局结构设计(图片图标就略了,这里暂用emoji(音标:/ɪˈmoʊdʒi/)绘文字代替):

<div class="uploadGroup">
    <label>
        <span class="uploadIco" title="上传图片">📷</span>
    </label>
    <a class="closeBtn" title="删除图片" hidden>❎</a>
</div>
<button onclick="getBase64Value()">GET VALUE</button>

JavaScript效果处理(选择图片,删除图片)

var picWrap = document.querySelector('.uploadGroup label');
var closeBtn = document.querySelector('.uploadGroup .closeBtn');
var obj = '<input type="file" accept="image/*" onchange="readFile(this)" hidden/>';
picWrap.insertAdjacentHTML('beforeend', obj);
// read file
function readFile(e) {
    var file = e.files[0];
    var reader = new FileReader();
    if (!file) {return;}
    reader.readAsDataURL(file);
    reader.onload = function() {
        picWrap.removeChild(e);
        closeBtn.removeAttribute('hidden');
        var pic = '<img src="'   this.result   '" alt="pic"/>';
        picWrap.insertAdjacentHTML('beforeend', pic);
    }
}
// delete it
closeBtn.addEventListener('click', function() {
    picWrap.removeChild(document.querySelector('img'));
    closeBtn.setAttribute('hidden', 'hidden');
    picWrap.insertAdjacentHTML('beforeend', obj);
}, false);
// base64 value
function getBase64Value() {
    var base64 = document.querySelector('.uploadGroup img').getAttribute('src');
    console.log(base64.match(/,(\S*)/)[1]);
}

最终,通过按钮获取到base64字符串请求上传接口提交即可。


html5 JavaScript 前端开发 上传图片 预览图片 上传图片 base64图片编码截取 FileReader异步读取文件 css3 accept文件类型

下一篇: