uniapp 打开文件管理器上传(H5、微信小程序、android app三端)文件

H5跟安卓APP 手机打开的效果图:

Vue页面:

html 复制代码
<template>
	<view class="content">
        <button @click="uploadFiles">点击上传</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {}
		},
		methods: {
			//h5、微信小程序、app上传文件
			uploadFiles() {
				//#ifdef H5
				uni.chooseFile({
					count: 1,
					extension: ['.doc,.xlsx,.docx'],
					success: res => {
						uni.showLoading({
							title: '导入中...',
							mask: true
						});
						uni.uploadFile({
							url: this.$BASE_URL + 'api/uploads/upload',
							file: res.tempFiles[0],
							name: 'file',
							success: (res) => {

							},
						});
					}
				});
				//#endif
				// #ifdef MP-WEIXIN
				uni.chooseMessageFile({
					count: 1, //默认100
					success: res => {
						uni.showLoading({
							title: '导入中...',
							mask: true
						});
						uni.uploadFile({
							url: this.$BASE_URL + 'api/uploads/upload',
							filePath: res.tempFiles[0].path,
							name: 'file',
							success: (res) => {

							},
						});
					}
				});
				//#endif
				// #ifdef APP-VUE
                //在这里导入打开安卓app本地文件选择器的封装方法
				this.$common.androidChooseFile(res => {
					var tempFiles = res;
					uni.uploadFile({
						url: this.$BASE_URL + 'api/uploads/upload',
						filePath: tempFiles,
						name: 'file',
						success: (res) => {

						}
					});
				},'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
				// #endif
			},
		},
	}
</script>

<style scoped></style>

封装的公共方法库utils/common.js:

javascript 复制代码
var common = {}
//安卓本地文件选择器
common.androidChooseFile = (callback, acceptType) => {
	var CODE_REQUEST = 1000;
	var main = plus.android.runtimeMainActivity();
	if (plus.os.name == 'Android') {
		var Intent = plus.android.importClass('android.content.Intent');
		var intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		if (acceptType) {
			intent.setType(acceptType);
		} else {
			intent.setType("*/*");
		}
		main.onActivityResult = (requestCode, resultCode, data) => {
			if (requestCode == CODE_REQUEST) {
				const uri = data.getData();
				plus.android.importClass(uri);
				const Build = plus.android.importClass('android.os.Build');
				const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
				const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
				if (isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
					if ("com.android.externalstorage.documents" == uri.getAuthority()) {
						console.log("6666");
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						var type = split[0];

						if ("primary" == type) {
							var Environment = plus.android.importClass('android.os.Environment');
							callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
						} else {
							var System = plus.android.importClass('java.lang.System');
							var sdPath = System.getenv("SECONDARY_STORAGE");
							if (sdPath) {
								callback(sdPath + "/" + split[1]);
							}
						}
					} else if ("com.android.providers.downloads.documents" == uri.getAuthority()) {
						var id = DocumentsContract.getDocumentId(uri);
						var ContentUris = plus.android.importClass('android.content.ContentUris');
						var contentUri = ContentUris.withAppendedId(
							//    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
							Uri.parse("content://downloads/public_downloads"), id);
						callback(getDataColumn(main, contentUri, null, null));
					} else if ("com.android.providers.media.documents" == uri.getAuthority()) {
						var docId = DocumentsContract.getDocumentId(uri);
						var split = docId.split(":");
						console.log(split);
						var type = split[0];
						console.log(type);
						var MediaStore = plus.android.importClass('android.provider.MediaStore');
						if ("image" == type) {
							contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
						} else if ("video" == type) {
							contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
						} else if ("audio" == type) {
							contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
						} else {
							contentUri = MediaStore.Files.getContentUri("external");
						}

						console.log(contentUri);
						var selection = "_id=?";
						var selectionArgs = new Array();
						selectionArgs[0] = split[1];

						callback(getDataColumn(main, contentUri, selection, selectionArgs));
					}
				} else if ("content" == uri.getScheme()) {
					callback(getDataColumn(main, uri, null, null));
				} else if ("file" == uri.getScheme()) {
					callback(uri.getPath());
				}
			}
		}
		main.startActivityForResult(intent, CODE_REQUEST);
	}

	function getDataColumn(main, uri, selection, selectionArgs) {
		plus.android.importClass(main.getContentResolver());
		let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs,
			null);
		plus.android.importClass(cursor);
		if (cursor != null && cursor.moveToFirst()) {
			var column_index = cursor.getColumnIndexOrThrow('_data');
			var result = cursor.getString(column_index)
			cursor.close();
			return result;
		}
		return null;
	}
}
export default common
相关推荐
王解41 分钟前
webpack loader全解析,从入门到精通(10)
前端·webpack·node.js
老码沉思录41 分钟前
写给初学者的React Native 全栈开发实战班
javascript·react native·react.js
我不当帕鲁谁当帕鲁1 小时前
arcgis for js实现FeatureLayer图层弹窗展示所有field字段
前端·javascript·arcgis
那一抹阳光多灿烂1 小时前
工程化实战内功修炼测试题
前端·javascript
放逐者-保持本心,方可放逐2 小时前
微信小程序=》基础=》常见问题=》性能总结
前端·微信小程序·小程序·前端框架
计算机-秋大田2 小时前
基于微信小程序的养老院管理系统的设计与实现,LW+源码+讲解
java·spring boot·微信小程序·小程序·vue
大耳猫3 小时前
主动测量View的宽高
android·ui
毋若成4 小时前
前端三大组件之CSS,三大选择器,游戏网页仿写
前端·css
红中马喽4 小时前
JS学习日记(webAPI—DOM)
开发语言·前端·javascript·笔记·vscode·学习
Black蜡笔小新5 小时前
网页直播/点播播放器EasyPlayer.js播放器OffscreenCanvas这个特性是否需要特殊的环境和硬件支持
前端·javascript·html