uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码)
一、PDF预览
1、下载PDF预览相关文件
- 下载地址
- 解压后效果:
2、使用步骤
- 在 static 文件夹下新建 pdf 文件夹,将解压文件放进 pdf 文件夹下(看网上很多博主把文件夹放在根目录里,我反正之前试到最后始终无法打开预览请求的PDF文件! 避坑 :放在 static 文件夹下就没问题了)
- 如图所示:
tool.js写打开pdf方法
//PDF文件预览-Android(IOS直接打开) openPDF : (filePath) => { //检查终端 uni.getSystemInfo({ success: function(e) { //如果是安卓用第三方 if (e.platform == 'android' || e.platform == 'windows') { //filepath带参数的 所以用缓存带过去 uni.setStorageSync('openPDF_filePath', filePath) uni.navigateTo({ url: `/pages/openPDF/index` }) } else { //ios直接打开pdf uni.showLoading({ title: '文档打开中...', mask: true }) uni.downloadFile({ url: filePath, complete: (res) => { uni.openDocument({ filePath: res.tempFilePath, success: function(e) { uni.hideLoading() console.log('打开文档成功'); } }); } }); } } }) },
页面/pages/openPDF/index
export default { data() { return { webViewUrl: '', } }, methods : { }, onLoad(options) { //https://www.sichewang.com/62a00a5e11c381654655582.pdf let path = uni.getStorageSync('openPDF_filePath') let fileUrl = encodeURIComponent(path) this.webViewUrl = `/static/openPDF/html/web/viewer.html?file=${fileUrl}` } }
main.js全局引入tool.js
import tool from '@/utils/tool' Vue.prototype.$tool = tool
使用
if (this.fjClickObj.file_name.includes('pdf')) { let url = this.$Api.url + '/get_uploads?sys=602&url=' + this.fjClickObj.url; console.log(url) this.$tool.openPDF(url) }
二、word、excle 预览
if (this.fjClickObj.file_name.includes('doc') || this.fjClickObj.file_name.includes('xls')) { let that = this let url = this.$Api.url + '/get_uploads?sys=602&url=' + this.fjClickObj.url; console.log(url) uni.downloadFile({ url: url, success: function(res) { let filepathss = plus.io.convertLocalFileSystemURL(res.tempFilePath); console.log(filepathss) setTimeout( () => uni.openDocument({ filePath: filepathss, showMenu: false, success: function() { console.log("打开文档成功"); }, fail: function() { uni.showToast({ title: '暂不支持此类型', duration: 2000, icon: "none", }); } }), 1000 ); }, fail: function(res) { console.log(res); //失败 } }); }
三、图片预览
1、简单预览
uni.previewImage({ current: index, urls: urls, success: function(e) { console.log('预览成功'); } })
2、预览加长按保存
//图片预览 previewImage : (urls, current = 0) => { uni.previewImage({ current: current, urls: urls, longPressActions: { itemList: ['保存图片'], success: function(data) { var url = urls[data.index] console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片'); // 先下载图片 uni.downloadFile({ url, success: (res) => { // 获取到图片本地地址后再保存图片到相册(因为此方法不支持远程地址) uni.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: () => { uni.showToast({ title: "保存成功!" , icon:'none'}); }, fail: () => { uni.showToast({ title: "保存失败", icon : 'none' }); }, }); }, }); } } }); },
四、附件上传(图片、PDF、word、excle)
uploadImg(eleName, index) { var vue = this; uni.getSystemInfo({ success: function(e) { vue.deviceType = e.platform } }) let device = this.deviceType.toLowerCase() == ('ios' || 'macos') ? 'ios' : 'android' console.log(device) if (device == 'android') { uni.showActionSheet({ itemList: ['选择图片', '选择文件'], success: (res) => { console.log(res) if (res.tapIndex == 0) { // 从相册中选 vue.$store.commit('setIsHideByChooseFile', true) uni.chooseImage({ count: 9, sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], //从相册选择 success: (image) => { console.log(image) var temp = '' if (image.tempFiles && image.tempFiles.length > 0) { image.tempFiles.forEach(item6 => { // #ifdef H5 temp = item6.name // #endif // #ifdef APP-PLUS temp = item6.path.substring(item6.path .lastIndexOf('/') + 1, item6.path .length) // #endif //H5 console.log(temp) //获取扩展名 var nameKZ = temp.substring(temp .lastIndexOf(".") + 1, temp.length); console.log(nameKZ); if (nameKZ.includes('doc') || nameKZ .includes('xls') || nameKZ.includes( 'pdf') || nameKZ.includes('png') || nameKZ.includes('jpg') || nameKZ .includes('jpeg') || nameKZ.includes( 'bmp')) {} else { uni.showToast({ title: '附件只能上传图片、pdf、word、excel', icon: 'none' }); return } let tempUrl = '' let tempName = '' //逐个上传 单张图片上传 uni.showLoading({ title: '附件上传中...' }); this.$Api.uploadFile([item6.path], 390000, res => { console.log(res) tempUrl = this.$Api.url + '/get_uploads?sys=602&url=' + res[0].file_path tempName = res[0].file_name console.log(tempUrl) let data = { url: tempUrl, file_url: res[0].file_path, file_name: tempName, file_size: (item6 .size / 1024) .toFixed(1) + 'kb', file_ext: temp .substring(temp .lastIndexOf( '.') + 1, temp.length) } this.arrs_otherProfile.push( data) console.log(this .arrs_otherProfile) this.$forceUpdate() uni.hideLoading(); }, e => { uni.hideLoading(); }) }) } } }); } else if (res.tapIndex == 1) { var _this = this // 选择文件 vue.$store.commit('setIsHideByChooseFile', true) chooseFile(url => { console.log(url) // /storage/emulated/0/DCIM/Screenshots/IMG_20221105_151817.jpg //获取扩展名 var nameKZ = url.substring(url.lastIndexOf(".") + 1, url.length); console.log(nameKZ); if (nameKZ.includes('doc') || nameKZ.includes( 'xls') || nameKZ.includes('pdf') || nameKZ .includes('png') || nameKZ.includes('jpg') || nameKZ.includes('jpeg') || nameKZ.includes( 'bmp')) { } else { uni.showToast({ title: '附件只能上传图片、pdf、word、excel', icon: 'none' }); return } //获取文件名 var name = url.substring(url.lastIndexOf("/") + 1, url.length); console.log(name); uni.showLoading({ title: '附件上传中...' }); _this.$Api.uploadFile([url], 390000, res => { console.log(res) let file_path = _this.$Api.url + '/get_uploads?sys=602&url=' + res[ 0].file_path let data = { url: file_path, file_url: res[0].file_path, file_name: name, file_ext: name.substring(name .lastIndexOf('.') + 1, name.length) } _this.arrs_otherProfile.push(data) console.log(_this.arrs_otherProfile) uni.hideLoading(); }, e => { console.log(e) uni.hideLoading(); }) }) } } }) } else if (device == 'ios') { vue.$store.commit('setIsHideByChooseFile', true) // 从相册中选 uni.chooseImage({ count: 9, sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], //从相册选择 success: (image) => { console.log(image) var temp = '' if (image.tempFiles && image.tempFiles.length > 0) { image.tempFiles.forEach(item6 => { // #ifdef H5 temp = item6.name // #endif // #ifdef APP-PLUS temp = item6.path.substring(item6.path.lastIndexOf('/') + 1, item6 .path.length) // #endif //H5 console.log(temp) //获取扩展名 var nameKZ = temp.substring(temp.lastIndexOf(".") + 1, temp .length); console.log(nameKZ); if (nameKZ.includes('doc') || nameKZ.includes('xls') || nameKZ .includes('pdf') || nameKZ.includes('png') || nameKZ.includes( 'jpg') || nameKZ.includes('jpeg') || nameKZ.includes('bmp')|| nameKZ.includes('BMP') || nameKZ.includes('JPEG') ||nameKZ.includes('JPG') ||nameKZ.includes('PNG') ) {} else { uni.showToast({ title: '附件只能上传图片、pdf、word、excel', icon: 'none' }); return } let tempUrl = '' let tempName = '' //逐个上传 单张图片上传 uni.showLoading({ title: '附件上传中...' }); this.$Api.uploadFile([item6.path], 390000, res => { console.log(res) tempUrl = this.$Api.url + '/get_uploads?sys=602&url=' + res[0].file_path tempName = res[0].file_name console.log(tempUrl) let data = { url: tempUrl, file_url: res[0].file_path, file_name: tempName, file_size: (item6.size / 1024).toFixed(1) + 'kb', file_ext: temp.substring(temp.lastIndexOf( '.') + 1, temp.length) } this.arrs_otherProfile.push(data) console.log(this.arrs_otherProfile) this.$forceUpdate() uni.hideLoading(); }, e => { // errorBack && errorBack(e) uni.hideLoading(); }) }) } } }); } },
Androd 选择附件的文件
var chooseFile = function(callback, acceptType) { var CODE_REQUEST = 1000; var main = plus.android.runtimeMainActivity(); if(plus.os.name == 'Android') { console.log("666"); 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)=>{ console.log(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; console.log(Build.VERSION.SDK_INT) console.log(Build.VERSION_CODES.KITKAT) const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract'); console.log(uri.getScheme()) if(isKitKat && DocumentsContract.isDocumentUri(main, uri)) { console.log(uri.getAuthority()) if("com.android.externalstorage.documents" == uri.getAuthority()) { console.log("6666"); var docId = DocumentsContract.getDocumentId(uri); var split = docId.split(":"); var type = split[0]; console.log(type); if("primary" == type) { var Environment = plus.android.importClass('android.os.Environment'); console.log(Environment.getExternalStorageDirectory() + "/" + split[1]); callback(Environment.getExternalStorageDirectory() + "/" + split[1]); } else { var System = plus.android.importClass('java.lang.System'); var sdPath = System.getenv("SECONDARY_STORAGE"); console.log(sdPath) if(sdPath) { callback(sdPath + "/" + split[1]); } } } else if("com.android.providers.downloads.documents" == uri.getAuthority()) { console.log("7777"); 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(getDataColumn(main, contentUri, null, null)); } else if("com.android.providers.media.documents" == uri.getAuthority()) { console.log("8888"); 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()) { console.log("9999"); console.log("9999",main); console.log("9999",uri); callback(getDataColumn(main, uri, null, null)); } else if("file" == uri.getScheme()) { console.log("0000"); console.log(uri.getPath()); 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); console.log(result); cursor.close(); return result; } return null; } export default chooseFile
附送250套精选项目源码
相关阅读:
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理!
部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!
图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!