原生input上传图片并预览
需求
上传图片,但后端不返回图片链接,返回加密的key值字符串,因此前端实现本地图片的预览。
实现
- 利用 window.URL.createObjectURl 获取上传图片的路径
- URL.createObjectURL() 静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的 URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的 URL 对象表示指定的 File 对象或 Blob 对象。
- 创建 FormData 对象实例,用于请求。
- append(key,value) 方法。如果key不存在会新增一条数据,如果key存在,则添加到数据末尾。
- window.URL.revokeObjectURL(url) 用于释放资源
DOM结构
<div v-if="showPic" style="position:relative;">
<viewer>
<img class="preview_box" :src="picSrc" alt="" />
</viewer>
<span class="delete_pic_box" @click="editPic">
<a-icon type="close" class="delete_icon_box" />
</span>
</div>
<div v-else style="position: relative;">
<button class="up_pic">
<a-icon type="camera" style="font-size: 22px;" />
</button>
<input
type="file"
accept="image/*"
@change="inputChange($event)"
class="upload_input"
/>
</div>
JS方法
inputChange(e) {
this.showPic = true // 展示预览dom
this.picSrc = window.URL.createObjectURL(e.target.files[0]) // 获取图片预览路径
let params = new FormData() // 用于请求
params.append("file", e.target.files[0])
uploadPrivateApi(params).then(({ data }) => {
this.formData.requestKey = data.fileKey
})
},
// 释放 URL 对象
beforeDestroy() {
window.URL.revokeObjectURL(this.picSrc)
},
样式
.up_pic {
width: 60px;
height: 60px;
border: 1px dotted rgba(0, 0, 0, 0.1);
background: rgba(0, 0, 0, 0.03);
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
// 覆盖input元素样式
.upload_input {
font-size: 0; // 隐藏文字,使 cursor: pointer 生效
opacity: 0; // 隐藏 input 框
position: absolute;
width: 80px;
left: -17px;
right: 0;
top: 0;
bottom: 0;
cursor: pointer;
}
.preview_box {
width: 60px;
height: 60px;
box-shadow: 2px 2px 4px rgba(140, 140, 140, 0.3);
cursor: pointer;
}
// 右上角删除小圆圈
.delete_pic_box {
position: absolute;
text-align: center;
top: -6px;
left: 49px;
display: inline-block;
height: 18px;
width: 18px;
border-radius: 50%;
background: #fff;
border: rgba(0, 0, 0, 0.2) solid 1px;
cursor: pointer;
&:hover {
border: #1890ff solid 1px;
}
.delete_icon_box {
position: absolute;
top: 3px;
right: 3px;
font-size: 10px;
&:hover {
color: #1890ff;
}
}
}
参考
JS实现本地图片预览的两种方式: blog.csdn.net/weixin_4627…