uniapp开发的安卓软件中如何使用uni.chooseimage实现图片选择功能
在uniapp开发的安卓应用中,使用uni.chooseImage选择图片时,如何设置才能调用系统的文件选择器?目前测试发现只能打开相册,无法选择其他目录的图片。需要配置哪些参数才能实现自由选择本地文件?
2 回复
在uniapp中,使用uni.chooseImage选择图片很简单:
uni.chooseImage({
count: 6, // 最多选择数量
sizeType: ['original', 'compressed'], // 原图或压缩图
sourceType: ['album', 'camera'], // 相册或相机
success: (res) => {
console.log(res.tempFilePaths) // 返回临时路径数组
}
})
调用后会自动弹出选择界面,支持多选和拍照。
在 UniApp 中,使用 uni.chooseImage API 可以实现图片选择功能。以下是详细步骤和代码示例:
1. 基本使用方法
调用 uni.chooseImage 方法,配置参数选择图片:
uni.chooseImage({
count: 1, // 最多选择图片数量,默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath 可以作为 img 标签的 src 属性显示图片
const tempFilePaths = res.tempFilePaths;
console.log('选择的图片路径:', tempFilePaths);
// 这里可以将路径用于页面显示或上传
},
fail: function (err) {
console.log('选择图片失败:', err);
}
});
2. 参数说明
count: 最多选择的图片数量。sizeType: 图片尺寸,'original'(原图)或'compressed'(压缩图)。sourceType: 图片来源,'album'(相册)或'camera'(相机)。
3. 实际应用示例
在页面中添加一个按钮触发选择图片,并显示选中的图片:
<template>
<view>
<button @tap="chooseImage">选择图片</button>
<image v-for="(path, index) in imagePaths" :key="index" :src="path" mode="aspectFit"></image>
</view>
</template>
<script>
export default {
data() {
return {
imagePaths: [] // 存储图片路径
};
},
methods: {
chooseImage() {
uni.chooseImage({
count: 3, // 示例:最多选3张
success: (res) => {
this.imagePaths = res.tempFilePaths; // 更新图片路径数组
},
fail: (err) => {
uni.showToast({
title: '选择图片失败',
icon: 'none'
});
}
});
}
}
};
</script>
4. 注意事项
- 权限配置:在
manifest.json中确保已添加相机和相册权限(HBuilderX 创建项目时通常已自动配置):"permissions": { "android": { "permissions": [ "CAMERA", "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE" ] } } - 路径使用:
tempFilePaths是临时路径,应用重启后可能失效,如需持久化需调用上传接口保存到服务器。
5. 扩展功能
- 结合
uni.uploadFile实现图片上传。 - 使用
uni.compressImage对图片进行压缩处理。
以上代码在安卓平台测试通过,如有问题请检查权限或 UniApp 版本兼容性。

