首页 > 编程技术 > js

uniapp组件uni-file-picker中设置使用照相机和相册权限的操作方法

发布时间:2022-11-15 13:51 作者:youmi_sunshine

在写uniapp项目中,对于上传图片有时会有这样的需求:只可使用照相机拍摄上传,不可使用相册。

在uniapp中,我们通常会使用uni-file-picker这个组件,但是这个组件中,有点缺陷,就是没有对这个功能的传值设置,这里就要给组件进行修改了。

1、在uni-file-picker组件中的uni-file-picker.vue中的js部分,找到props添加一个变量,如下:

props: {
		....以上省略	
			sizeType: {
				type: Array,
				default () {
					return ['original', 'compressed']
				}
			},
 
            //这是新加的变量,默认值是相册和照相机都有的
			sourceType: {
				type: Array,
				default () {
					return ['camera','album']
				}
			}
},

2、在uni-file-picker组件中的uni-file-picker.vue中的js部分,找到chooseFiles()函数,添加sourceType的传值,如下:

/**
 * 选择文件并上传
*/
chooseFiles() {		
	const _extname = get_extname(this.fileExtname)
	// 获取后缀
	uniCloud
		.chooseAndUploadFile({
				type: this.fileMediatype,
				compressed: false,
                //sourceType为新添加的控制照相机与相册的传值变量
				sourceType: this.sourceType,
				sizeType: this.sizeType,
				// TODO 如果为空,video 有问题
				extension: _extname.length > 0 ? _extname : undefined,
				count: this.limitLength - this.files.length, //默认9
				onChooseFile: this.chooseFileCallback,
				onUploadProgress: progressEvent => {
					this.setProgress(progressEvent, progressEvent.index)
				}
		})
		.then(result => {
			this.setSuccessAndError(result.tempFiles)
		})
		.catch(err => {
			console.log('选择失败', err)
		})
},

3、在页面调用模板中使用改组件,使用 :sourceType或者 :source-type来控制照相机与相册的使用权限,如下:

<template>
	<view class="container">
        <!--设置只能使用照相机  :sourceType="sourceType1" -->
        <view class="upload-box">
			<view class="pic-desc">照片1</view>
			<uni-file-picker  v-model="mentouValue" return-type="object" fileMediatype="image" mode="grid" :sourceType="sourceType1" :auto-upload="false"  @select="mentouSelect" @delete="mentouDelete"/>	
		</view>
        <!--设置只能使用照相机 则 :sourceType="sourceType2" -->
        <!--若都可以使用,则不用此变量,默认都可以使用的-->
    </view>
<template>

4、js部分写法如下:

<script>
export default {
	data() {
		return{
           mentouValue:'',
           sourceType1:['camera'], 
           sourceType2:['album'], 
        }
    },
    methods:{
        //选择图片
        mentouSelect(e){
			console.log("选择图片",e)
		},
 
        //删除图片
        mentouDelete(){
			this.mentouValue = ''
		},
    }
}
</script>

到此这篇关于uniapp组件uni-file-picker中设置使用照相机和相册的权限的文章就介绍到这了,更多相关uniapp组件uni-file-picker相册权限内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/youmi_sunshine/article/details/1259276

标签:[!--infotagslink--]

您可能感兴趣的文章: