700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Vue 移动端调用相机和相册实现图片上传

Vue 移动端调用相机和相册实现图片上传

时间:2022-02-16 04:25:14

相关推荐

Vue 移动端调用相机和相册实现图片上传

一、基础知识:

1.只调用手机相册

<input type="file" accept="image/*;" >

2.只调用手机相机拍照

<input type="file" accept="image/*" capture="camera">

3.调用手机相册和拍照

<input type="file" accept="image/*">

二、项目代码:

思路:通过input标签调用手机的相册相机功能,获取图片文件,通过formdata传给后台,后台返回图片路径,获取图片路径显示在页面上。

注意:因为直接用input标签样式不太好看,也不符合UI的设计需求,所以这里将调取手机相册和相机的input框隐藏了,然后点击下边的标签触发input事件

代码:

template

<input class="hide_file" ref ="leftFile" id="upload" type="file" @change="getFile($event)" accept="image/*"><div class="camera" @click="clickFile"><img v-if="img" class="bigImg" :src="img" alt=""><img v-if="!img" class="icon" src="~@/assets/img/icon_camera.png" alt=""><span v-if="!img" class="text">上传照片</span></div>

js

methods:{ // 获取选择的图片文件上传getFile(e) {let file = e.target.files[0]; console.log(file);let param = new FormData(); //创建form对象param.append('file',file,file.name);//通过append向form对象添加数据 param.append("id",this.token); console.log(file);let config = {headers:{'Content-Type':'multipart/form-data',}}; //添加请求头axios.post('/wx/goods/uploadPicture',param,config) .then(res=>{if(res.data.code==0){this.img = res.data.url;this.newImg = res.data.url;// this.$Message.success(res.data.msg) }else{// this.$Message.error(res.data.msg)}}) },// 点击触发input的点击事件clickFile(){this.$refs.leftFile.click();},}

css

.hide_file{display:none;}.camera{position: relative;z-index: 2;margin: 0 auto;margin-bottom: 10px;width: 138px;height: 138px;background: #E7E7E7;border-radius: 6px;text-align: center;.bigImg{width: 138px;height: 138px;}.icon{width: 40px;margin-top: 40px;}.text{display: block;line-height: 22px;font-size: 15px;color: #999;margin-top: 8px;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。