由于uniapp提供的API在app端只能上传图片和视频,不能上传其他文件,说以只能借助插件了。
ios端用的这个插件 获取到文件对象 免费的
这个是返回一个 filePath 可用直接用于 uni.uploadFile 上传的路径,后面自己又改的File对象 全文件上传选择非原生2.0版 - DCloud 插件市场文件选择上传-支持APP-H5网页-微信小程序https://ext.dcloud.net.cn/plugin?id=5459
安卓部分主要通过使用 Android 平台的相关类来实现选择文件和获取文件本地路径的功能,使用这些原生 Android 的类和方法,代码能够处理不同类型的文件选择器返回的文件 URI,并获取文件的本地路径。根据文件的 URI 类型和授权部分,代码执行相应的处理逻辑,从而实现选择文件和获取文件本地路径、File对象的功能。
微信小程序和H5那就简单了uniapp提供的API就可以
<template><view class=""><view class="" @click="sendFile"><text>获取文件</text></view></view>
</template>
methods: {sendFile() {// #ifdef H5uni.chooseFile({count: 1,// extension:['.zip','.doc'],success: (res) => {console.log(res);console.log('file:', res.tempFiles[0]); // File对象}});// #endif// #ifdef MP-WEIXINconsole.log('WEIXIN');wx.chooseMessageFile({count: 10,type: 'file',success: (res) => {console.log('file:', res.tempFiles[0]); // File对象}})// #endif// #ifdef APP-PLUSswitch (uni.getSystemInfoSync().platform) {case 'android':this.chooseFile((path) => {console.log('文件本地路径:', path);plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {fs.root.getFile(path, {create: true}, (fileEntry) => {fileEntry.file((file) => {let fileReader = new plus.io.FileReader();console.log(file);console.log(fileReader);console.log("文件对象:" + JSON.stringify(file)); // File对象}, (error) => {console.log("读写出现异常", error);});});});})break;case 'ios':this.filePathIos()break;}// #endif},// ios 选择文件filePathIos() {// 示例代码:const iOSFileSelect = uni.requireNativePlugin('YangChuan-YCiOSFileSelect');// apple document-types 文件类型参数 https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html// 文件类型参数let params = {"document-types": ["public.text", "public.zip", "public.data", "com.adobe.pdf","com.microsoft.word.doc", "com.adobe.postscript", "com.microsoft.excel.xls","com.adobe.encapsulated- postscript", "com.microsoft.powerpoint.ppt","com.adobe.photoshop- image", "com.microsoft.word.rtf", "com.microsoft.advanced- systems-format","com.microsoft.advanced- stream-redirector"],"isBase64": 0}iOSFileSelect.show(params, result => {let status = parseInt(result.status);// 状态200选取成功if (status == 200) {let url = result.url;uni.downloadFile({url: url,success: (res) => {if (res.statusCode == 200) {// filePath 可用于 uni.uploadFile 上传的路径let filePath = res.tempFilePath;let name = filePath.split("/")[filePath.split("/").length - 1];console.log(result);const uploadTask = uni.uploadFile({url: 'https://上传接口', //仅为示例,非真实的接口地址filePath: filePath,name: 'file',formData: {'user': 'test'},success: (uploadFileRes) => {console.log(uploadFileRes.data);}});uploadTask.onProgressUpdate((res) => {console.log(res);console.log('上传进度' + res.progress);console.log('已经上传的数据长度' + res.totalBytesSent);console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);// 测试条件,取消上传任务。if (res.progress > 1) {uploadTask.abort();let size = res.totalBytesExpectedToSendlet file = {path: filePath,name: name,size: size,type: 'file'}console.log(file); // File对象}});}}});}});},// 安卓选择文件chooseFile(callback) {console.log('choodeFile')var CODE_REQUEST = 1000;var main = plus.android.runtimeMainActivity();var Intent = plus.android.importClass('android.content.Intent');var intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("*/*");main.onActivityResult = (requestCode, resultCode, data) => {if (requestCode == CODE_REQUEST) {var uri = data.getData();console.log('uri:', uri)// uri是编码过的,需要转换为本地路径plus.android.importClass(uri);var Build = plus.android.importClass('android.os.Build');var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;var DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');if (isKitKat && DocumentsContract.isDocumentUri(main, uri)) {// DocumentProviderconsole.log('getAuthority:', uri.getAuthority())if (uri.getAuthority() == "com.android.externalstorage.documents") {// ExternalStorageProviderlet docId = DocumentsContract.getDocumentId(uri);let split = docId.split(":");let type = split[0];if (type === "primary") {let Environment = plus.android.importClass('android.os.Environment');callback(Environment.getExternalStorageDirectory() + "/" + split[1]);} else {let System = plus.android.importClass('java.lang.System');let sdPath = System.getenv("SECONDARY_STORAGE");if (sdPath) {callback(sdPath + "/" + split[1]);}}} else if (uri.getAuthority() == "com.android.providers.downloads.documents") {// DownloadsProvidervar id = DocumentsContract.getDocumentId(uri);var ContentUris = plus.android.importClass('android.content.ContentUris');var contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);callback(this.getDataColumn(main, contentUri, null, null));} else if (uri.getAuthority() == "com.android.providers.media.documents") {// MediaProvidervar docId = DocumentsContract.getDocumentId(uri);console.log('docId:', docId)var split = docId.split(":");var type = split[0];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;}var selection = "_id=?";var selectionArgs = new Array();selectionArgs[0] = split[1];callback(this.getDataColumn(main, contentUri, selection, selectionArgs))}} else if (uri.getScheme() == "content") {if (uri.getAuthority() == "media") {callback(this.getDataColumn(main, uri, null, null));} else {callback(uri.getPath());}} else if (uri.getScheme() == "file") {// Fileconsole.log("file");callback(uri.getPath());}}}main.startActivityForResult(intent, CODE_REQUEST);},// main, uri, selection, selectionArgsgetDataColumn(main, uri, selection, selectionArgs) {plus.android.importClass(main.getContentResolver());var 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;}}