由于uniapp提供的API在app端只能上传图片和视频,不能上传其他文件,说以只能借助插件了。
ios端用的这个插件 获取到文件对象 免费的
ios-uniapp 文件选取word,pdf,xls等文件 - DCloud 插件市场uniapp iOS文件选取 iOS选取text,pdf,word,doc,xls,ppthttps://ext.dcloud.net.cn/plugin?id=1311
这个是返回一个 filePath 可用直接用于 uni.uploadFile 上传的路径,后面自己又改的File对象。
安卓部分主要通过plus 对象,来调用原生文件系统管理器来选取文件,并获取文件的路径和文件对象。调用 pickFile.PickFile 方法来选取文件,使用plus.io.resolveLocalFileSystemURL方法。该方法用于将本地文件路径转换为文件系统 URL,并返回对应的 FileEntry 对象。文章来源:https://www.toymoban.com/news/detail-562625.html
微信小程序和H5那就简单了uniapp提供的API就可以文章来源地址https://www.toymoban.com/news/detail-562625.html
示例代码:
<template>
<view class="">
<view class="" @click="sendFile">
<text>获取文件</text>
</view>
</view>
</template>
methods: {
sendFile() {
// #ifdef H5
uni.chooseFile({
count: 1,
// extension:['.zip','.doc'],
success: (res) => {
console.log(res);
console.log('file:', res.tempFiles[0]); // File对象
// 可以在这里进行后续操作
}
});
// #endif
// #ifdef MP-WEIXIN
console.log('WEIXIN');
wx.chooseMessageFile({
count: 10,
type: 'file',
success: (res) => {
console.log('file:', res.tempFiles[0]); // File对象
// 可以在这里进行后续操作
}
})
// #endif
// #ifdef APP-PLUS
switch (uni.getSystemInfoSync().platform) {
case 'android':
let permisionID = 'android.permission.READ_EXTERNAL_STORAGE'
permision.requestAndroidPermission(permisionID)
.then(res => {
if (res == 1) {
this.chooseFileAndroid()
} else {
uni.showModal({
title: '无法访问存储',
content: '您已经关闭存储权限,您已经关闭存储权限,请在"设置-隐私-存储"中允许访问存储',
success: (res) => {
if (res.confirm) {
// plus.runtime.openURL("package:");
} else if (res.cancel) {
plus.runtime.openURL("package:");
console.log('用户点击取消');
}
}
});
}
})
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.totalBytesExpectedToSend
let file = {
path: filePath,
name: name,
size: size,
type: 'file'
}
console.log(file); // File对象
// 可以在这里进行后续操作
}
});
}
}
});
}
});
},
// 安卓选择文件
chooseFileAndroid() {
/* eslint-disable */
//调用原生文件系统管理器并选取文件获取文件地址
var pickFile = {
PickFile: function(callback,
mimeTypes
) {
/*
acceptType为你要查的文件类型"image/*","audio/*","video/*;image/*"
intent.setType("image/*");
intent.setType("audio/*");
选择音频 intent.setType("video/*;image/*");
选择视频 (mp4 3gp 是android支持的视频格式)
*/
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 (mimeTypes) {
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
} else {
intent.setType("*/*");
}
let _this = pickFile;
main.onActivityResult = function(requestCode, resultCode, data) {
if (requestCode == CODE_REQUEST) {
var uri = data.getData();
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)) {
console.log("版本大于 4.4");
if ("com.android.externalstorage.documents" == uri.getAuthority()) {
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"), id);
callback(_this.getDataColumn(main, contentUri, null, null));
} else if ("com.android.providers.media.documents" == uri.getAuthority()) {
var docId = DocumentsContract.getDocumentId(uri);
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;
} else {
contentUri = MediaStore.Files.getContentUri("external");
}
console.log("版本大于 4.4", type);
var selection = "_id=?";
var selectionArgs = new Array();
selectionArgs[0] = split[1];
callback(_this.getDataColumn(main, contentUri, selection, selectionArgs));
}
} else if ("content" == uri.getScheme()) {
callback(_this.getDataColumn(main, uri, null, null));
} else if ("file" == uri.getScheme()) {
callback(uri.getPath());
}
}
}
main.startActivityForResult(intent, CODE_REQUEST);
}
},
getDataColumn: function(main, uri, selection, selectionArgs) {
plus.android.importClass(main.getContentResolver());
let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs, null);
plus.android.importClass(cursor);
console.log(cursor);
if (cursor != null && cursor.moveToFirst()) {
var column_index = cursor.getColumnIndexOrThrow('_data');
var result = cursor.getString(column_index)
cursor.close();
return result;
}
return null;
}
}
/* eslint-disable no-new */
// 拿到文件路径后,获取文件对象file
pickFile.PickFile((path) => {
//返回的路径
console.log(path);
plus.io.resolveLocalFileSystemURL(path, (entry) => {
entry.file((file) => {
// file 对象即为所需的文件对象
console.log("文件对象:", file);
// 可以在这里进行后续操作
}, (error) => {
console.log("获取文件对象出现异常", error);
});
}, (error) => {
console.log("解析本地文件路径出现异常", error);
});
}, '*/*')
},
}
到了这里,关于uniapp 发送全文件 支持App端ios、android,微信小程序,H5的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!