安卓选择文件

更新时间: 2025-09-19 10:20:32

选择文件我做了H5版和安卓版的,H5版就是uni.chooseFile, 安卓版的我使用了插件市场的插件

看代码的注释应该就懂了,并不需要多余的解释了

import { chooseFileFromModule } from '@/uni_modules/sr-file-choose'	

// 储存选中的文件信息  
const list = []

// 选择文件
function chooseFile() {
	 // #ifdef H5
	 uni.chooseFile({
	 		count: 1, // 每次选择1个文件
	 		extension: ['doc', 'docx', 'pdf', 'xlsx', 'xls'], // 允许的文件后缀
	 		success: (res) => {
	 		  const file = res.tempFiles[0];
	 		  
	 		  // 检查文件大小(20MB = 20 * 1024 * 1024 = 20971520 bytes)
	 		  if (file.size > 100 * 1024 * 1024) {
	 			uni.showToast({
	 			  title: '文件大小不能超过100MB',
	 			  icon: 'none'
	 			});
	 			return;
	 		  }
	 		  
	 		  // 添加到已上传列表
	 		  list.push({
	 			name: file.name,
	 			path: file.path,
	 			size: file.size
	 		  });
	 
	 		},
	 		fail: (err) => {
	 		  console.error('选择文件失败', err);
	 		  uni.showToast({ title: '选择文件失败', icon: 'none' });
	 		}
	 });
	 // #endif
	 
	 // #ifdef APP
	 chooseFileFromModule({
	 	complete: (res) => {
	 		 let path = res.path                            
	 		 let name = res.name
	 		 let fileType = ''
             //1. 处理文件名  
	 		// 如果没有name,默认为:截取最后一个/之后的内容
	 		if(!name) {
	 			let lastIndex = path.lastIndexOf('/');
	 			if (lastIndex !== -1) {
	 				name = path.substring(lastIndex + 1);
	 			} else {  
                    // 随机生成文件名  
	 				name = Math.random().toString(36).substr(2) + Date.now();
	 			}
	 		}
            // 2. 提取文件扩展名  
	 		// 使用 lastIndexOf 方法找到最后一个 . 的位置
	 		let lastDotIndex = name.lastIndexOf('.');
	 		if (lastDotIndex !== -1) {
	 			fileType = name.substring(lastDotIndex + 1);
	 		} else {
	 			console.log('文件路径中没有 .');
	 		}

            // 3. 验证文件类型  
	 		const typeList = ['doc', 'docx', 'pdf', 'xlsx', 'xls']
	 		if(typeList.indexOf(fileType) == -1) {
	 			uni.showToast({ title: '请选择正确的文件格式', icon: 'none' });
	 		}else{
	 			list.push({
	 			 	name: res.name,
	 			 	path: res.path,
	 			 	size: res.size
	 			});
	 		}
	 	}
	 })
	 // #endif
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79