移动端拍照并上传
2018-02-24 本文已影响15人
bennnnn
自己开发的移动端拍照上传图片代码(自己总结收藏一下),我用的是pug+less语法,可以自己转成html+css,或者是.vue文件。
需要添加一个图片压缩库lrz
执行npm i lrz(推荐)
或者直接引入<script src="./dist/lrz.bundle.js"></script>
拍照并压缩上传.png
pug
ul.list-ul
li.list-li(v-for="(customizationImg,index) in customizationOptions.images")
a.list-link(@click='previewImage(customizationImg.url)')
img(:src="customizationImg.url")
li.list-li(v-show="customizationOptions.images.length!==5")
img.upload-img(src="/assets/img/upload.png")
input#choose-img(type="file",accept="image/jpg,image/jpeg,image/png",capture="camera",@change="onFileChangeCustomization")
less
.list-li {
display: inline;
margin: 0 5px;
position: relative;
.upload-img {
width: 50px;
}
#choose-img {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0;
}
.delete {
position: absolute;
top: -30px;
right: -8px;
width: 15px;
height: 15px;
background-color: @golden-color;
text-align: center;
border-radius: 50%;
i {
position: absolute;
top: 4px;
left: 2px;
font-size: 10px;
color: #fff;
text-align: center;
line-height: 8px;
}
}
img {
width: 50px;
}
}
js
data() {
return {
customizationOptions: []
}
},
methods: {
onFileChangeCustomization(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.createImage(files, e);
},
createImage: function (file, e) {
this.loading = true;
return Promise.resolve()
.then(() => {
return lrz(file[0], {
width: 1000
});
})
.then(() => {
//服务器如果需要上传blob,就将base64转成blob再传
// let blobImg = this.convertBase64UrlToBlob(rst.base64);
this.customizationOptions.push({
url: rst.base64,
id: ''
})
})
.finally(() => {
// 清空文件上传控件的值
e.target.value = null;
});
},
previewImage(url) {
this.cameraImgPreviewVisible = true;
this.previewImg = url;
},
deleteImg(id, type) {
this.loading = true;
return Promise.resolve()
.then(() => {
return this.currentCustomization.customization.deleteImage(id);
}).then(() => {
this.loading = false;
});
},
convertBase64UrlToBlob(urlData) {
let bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
}