vue选择本地文件或者Ctrl+v粘贴截图上传
场景:因为最近项目里要求用户上传本地图片,并且既可以从本地选取,也可以直接粘贴截图,所以就研究了一下,顺便分享给大家。
- html部分
<div style="margin: 15px 0px 15px;">
<div>
<div class="choose-localImg">
选择凭证
<input ref="InputFile" class="file-ipt" type="file" name="files" accept="image/*" @change="chooseRecoverLocal($event)">
</div>
<div class="img-paste" @paste="handlePaste">
将图片按Ctrl+V 粘贴至此处
</div>
<div v-for="(item,index) in payImageList" :key="index" style="margin-top: 10px;">
<div style="position: relative;width: 60%;margin: auto;">
<div class="remove-img" @click="removePayImage(index)">X</div>
<img style="width:100%" :src="baseUrl + item">
</div>
</div>
<!--<img v-if="recoverImg" :src="baseUrl+recoverImg" style="width: 60%;">-->
</div>
</div>
- js
data(){
return {
payImageList: [], // 选择的出纳图片列表
baseUrl: baseUrl // 服务器地址
}
}
methods:{
// 按钮选择本地图片
chooseRecoverLocal(e) {
const file = e.target.files[0]
const formData = new FormData() // 创建 formdata对象
formData.append('image', file)
formData.append('processData', false)
// 调用后台上传服务器接口
upLoadImgService.uploadCertificate(formData).then(res => {
if (res.code === '0') {
const payImage = res.content[0]
this.payImageList.push(payImage)
}
})
},
// 获取出纳粘贴图片
handlePaste(event) {
const items = (event.clipboardData || window.clipboardData).items
let file = null
if (!items || items.length === 0) {
this.$message.error('当前浏览器不支持本地或请打开图片再复制')
return
}
// 搜索剪切板items
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile()
break
}
}
if (!file) {
this.$message.error('粘贴内容非图片')
return
}
var formRrcover = new FormData()
formRrcover.append('image', file)
formRrcover.append('processData', false)
upLoadImgService.uploadCertificate(formRrcover).then(res => {
if (res.code === '0') {
const payImage = res.content[0]
this.payImageList.push(payImage)
}
})
},
// 移除添加的图片
removePayImage(index) {
this.payImageList.splice(index, 1)
},
}
3.css
.choose-localImg{
width: 96px;
height: 39px;
vertical-align: middle;
background: #1890ff;
color: #ffffff;
border: 0;
border-radius: 3px;
font-size: 14px;
text-align: center;
line-height: 39px;
display: inline-block;
position: relative;
}
.file-ipt{
height: 39px;
vertical-align: middle;
position: absolute;
left: 0;
cursor: pointer;
z-index: 2;
width: 96px;
border: 1px solid red;
overflow: hidden;
opacity: 0;
}
.img-paste{
display: inline-block;
border: 1px solid #396fff;
height: 39px;
vertical-align: middle;
line-height: 39px;
padding: 0px 14px;
color: #c2c0c0;
font-size: 13px;
}
.remove-img {
position: absolute;
width: 33px;
height: 33px;
background: #4c504d;
color: #ffffff;
line-height: 33px;
text-align: center;
font-size: 21px;
right: 0;
}
4.效果图