1.看文档
上面说的调取图片或视频拾取模式 用caputure
代码如下
<template>
<view>
<u-upload
:capture="['camera','album']"
:max-count="1"
:preview-size="100"
:preview-image="true"
:fileList=" images"
@afterRead="afterRead"
>
<view class="u-upload__tip">上传图片</view>
</u-upload>
</view>
</template>
<script>
export default {
data() {
return {
images: [],
};
},
methods: {
//上传图片
afterRead(event) {
console.log(event);
if (event.file.size / 1024 / 1024 > 2) {
this.$refs.uToast.show({
type: 'error',
message: "上传图片大小不能超过 2MB!",
})
} else if (event.file.thumb.includes("jpg") || event.file.thumb.includes("png")) {
this.images.push(event.file);
pathToBase64(event.file.url)
.then(base64 => {
this.model1.url.push(base64)
})
.catch(error => {
console.error(error)
})
} else {
this.$refs.uToast.show({
type: 'error',
message: "上传头像图片只能是 JPG/PNG 格式!",
})
}
},
}
};
</script>
我用的方法是调取手机打开相册功能和拍照功能 然后回调获取到的url 转成base64 得格式 最后和表单一起提交给后端 当然你也可以调取 uni.uploadFile 直接先将图片上传给后端
遇到bug :
以上代码上传以后 在微信小程序里电脑、安卓都可以支持调取功能 但是ios支持不了
如何解决:
解决方法很简单
在以上代码 将html改成
<view>
<u-upload
:source-type="['camera','album']"
:capture="['camera',’album']"
:max-count="1"
:preview-size="100"
:preview-image="true"
:fileList=" images"
@afterRead="afterRead"
>
<view class="u-upload__tip">上传图片</view>
</u-upload>
</view>
也就是加上 :source-type="['camera','album']" 就可以了
capture表示,可以捕获到系统默认的设备,比如:camera--照相机;camcorder--摄像机;microphone--录音。(捕获系统默认设备)
sourceType或者 :source-type 控制照相机与相册的使用权限,可以指定来源是相册album还是相机camera,默认二者都有(控制使用权限)
accept表示,直接打开系统文件目录
注意:
微信中ios内置的浏览器是完全支持的
android中必须加上accept最好也加上capture