uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)( ...

金歌  论坛元老 | 2024-6-26 05:20:06 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1052|帖子 1052|积分 3156

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、PDF预览

1、下载PDF预览相关文件



  • 下载地址
  • 解压后结果:

2、使用步骤



  • 在  static  文件夹下新建  pdf  文件夹,将解压文件放进  pdf  文件夹下(看网上很多博主把文件夹放在根目次里,我反正之前试到最后始终无法打开预览请求的PDF文件!  避坑  :放在  static 文件夹下就没问题了)
  • 如图所示:

tool.js写打开pdf方法

  1. //PDF文件预览-Android(IOS直接打开)
  2.         openPDF : (filePath) => {
  3.                 //检查终端
  4.                 uni.getSystemInfo({
  5.                         success: function(e) {
  6.                                 //如果是安卓用第三方
  7.                                 if (e.platform == 'android' || e.platform == 'windows') {
  8.                                         //filepath带参数的 所以用缓存带过去
  9.                                         uni.setStorageSync('openPDF_filePath', filePath)
  10.                                         uni.navigateTo({
  11.                                                 url: `/pages/openPDF/index`
  12.                                         })
  13.                                 } else {
  14.                                         //ios直接打开pdf
  15.                                         uni.showLoading({
  16.                                                 title: '文档打开中...',
  17.                                                 mask: true
  18.                                         })
  19.                                         uni.downloadFile({
  20.                                                 url: filePath,
  21.                                                 complete: (res) => {
  22.                                                         uni.openDocument({
  23.                                                                 filePath: res.tempFilePath,
  24.                                                                 success: function(e) {
  25.                                                                         uni.hideLoading()
  26.                                                                         console.log('打开文档成功');
  27.                                                                 }
  28.                                                         });
  29.        
  30.                                                 }
  31.                                         });
  32.                                 }
  33.                         }
  34.                 })
  35.         },
复制代码
页面/pages/openPDF/index

  1. <template>
  2.         <view style="width: 100%;" >
  3.                 <web-view  :src="webViewUrl"></web-view>
  4.         </view>
  5. </template>
  6. <script>
  7. export default {
  8.         data() {
  9.                 return {
  10.                         webViewUrl: '',
  11.                 }
  12.         },
  13.         methods : {
  14.         },
  15.         onLoad(options) {
  16.                 //https://www.sichewang.com/62a00a5e11c381654655582.pdf
  17.                 let path = uni.getStorageSync('openPDF_filePath')
  18.                 let fileUrl = encodeURIComponent(path)
  19.                 this.webViewUrl = `/static/openPDF/html/web/viewer.html?file=${fileUrl}`
  20.         }
  21. }
  22. </script>
  23. <style>
  24. </style>
复制代码
main.js全局引入tool.js

  1. import tool from '@/utils/tool'
  2. Vue.prototype.$tool = tool
复制代码
使用

  1. if (this.fjClickObj.file_name.includes('pdf')) {
  2.                                         let url = this.$Api.url + '/get_uploads?sys=602&url=' + this.fjClickObj.url;
  3.                                         console.log(url)
  4.                                         this.$tool.openPDF(url)
  5.                                 }
复制代码

二、word、excle 预览

  1. if (this.fjClickObj.file_name.includes('doc') || this.fjClickObj.file_name.includes('xls')) {
  2.                                         let that = this
  3.                                         let url = this.$Api.url + '/get_uploads?sys=602&url=' + this.fjClickObj.url;
  4.                                         console.log(url)
  5.                                         uni.downloadFile({
  6.                                                 url: url,
  7.                                                 success: function(res) {
  8.                                                         let filepathss = plus.io.convertLocalFileSystemURL(res.tempFilePath);
  9.                                                         console.log(filepathss)
  10.                                                         setTimeout(
  11.                                                                 () =>
  12.                                                                 uni.openDocument({
  13.                                                                         filePath: filepathss,
  14.                                                                         showMenu: false,
  15.                                                                         success: function() {
  16.                                                                                 console.log("打开文档成功");
  17.                                                                         },
  18.                                                                         fail: function() {
  19.                                                                                 uni.showToast({
  20.                                                                                         title: '暂不支持此类型',
  21.                                                                                         duration: 2000,
  22.                                                                                         icon: "none",
  23.                                                                                 });
  24.                                                                         }
  25.                                                                 }),
  26.                                                                 1000
  27.                                                         );
  28.                                                 },
  29.                                                 fail: function(res) {
  30.                                                         console.log(res); //失败
  31.                                                 }
  32.                                         });
  33.                                 }
复制代码

三、图片预览

1、简朴预览

  1. uni.previewImage({
  2.                                                 current: index,
  3.                                                 urls: urls,
  4.                                                 success: function(e) {
  5.                                                         console.log('预览成功');
  6.                                                 }
  7.                                         })
复制代码
2、预览加长按生存

  1. //图片预览
  2.         previewImage : (urls, current = 0) => {
  3.                 uni.previewImage({
  4.                         current: current,
  5.                         urls: urls,
  6.                         longPressActions: {
  7.                                 itemList: ['保存图片'],
  8.                                 success: function(data) {
  9.                                         var url = urls[data.index]
  10.                                         console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
  11.                                         // 先下载图片
  12.                                         uni.downloadFile({
  13.                                             url,
  14.                                             success: (res) => {
  15.                                                 // 获取到图片本地地址后再保存图片到相册(因为此方法不支持远程地址)
  16.                                                 uni.saveImageToPhotosAlbum({
  17.                                                     filePath: res.tempFilePath,
  18.                                                     success: () => {
  19.                                                                         uni.showToast({ title: "保存成功!" , icon:'none'});
  20.                                                     },
  21.                                                     fail: () => {
  22.                                                                         uni.showToast({ title: "保存失败", icon : 'none' });
  23.                                                     },
  24.                                                 });
  25.                                             },
  26.                                         });
  27.                                 }
  28.                         }
  29.                 });
  30.         },
复制代码

四、附件上传(图片、PDF、word、excle)

  1. uploadImg(eleName, index) {
  2.                                 var vue = this;
  3.                                 uni.getSystemInfo({
  4.                                         success: function(e) {
  5.                                                 vue.deviceType = e.platform
  6.                                         }
  7.                                 })
  8.                                 let device = this.deviceType.toLowerCase() == ('ios' || 'macos') ? 'ios' : 'android'
  9.                                 console.log(device)
  10.                                 if (device == 'android') {
  11.                                         uni.showActionSheet({
  12.                                                 itemList: ['选择图片', '选择文件'],
  13.                                                 success: (res) => {
  14.                                                         console.log(res)
  15.                                                         if (res.tapIndex == 0) {
  16.                                                                 // 从相册中选
  17.                                                                 vue.$store.commit('setIsHideByChooseFile', true)
  18.                                                                 uni.chooseImage({
  19.                                                                         count: 9,
  20.                                                                         sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  21.                                                                         sourceType: ['album'], //从相册选择
  22.                                                                         success: (image) => {
  23.                                                                                 console.log(image)
  24.                                                                                 var temp = ''
  25.                                                                                 if (image.tempFiles && image.tempFiles.length > 0) {
  26.                                                                                         image.tempFiles.forEach(item6 => {
  27.                                                                                                 // #ifdef H5
  28.                                                                                                 temp = item6.name
  29.                                                                                                 // #endif
  30.                                                                                                 // #ifdef APP-PLUS
  31.                                                                                                 temp = item6.path.substring(item6.path
  32.                                                                                                         .lastIndexOf('/') + 1, item6.path
  33.                                                                                                         .length)
  34.                                                                                                 // #endif
  35.                                                                                                 //H5
  36.                                                                                                 console.log(temp)
  37.                                                                                                 //获取扩展名
  38.                                                                                                 var nameKZ = temp.substring(temp
  39.                                                                                                         .lastIndexOf(".") + 1, temp.length);
  40.                                                                                                 console.log(nameKZ);
  41.                                                                                                 if (nameKZ.includes('doc') || nameKZ
  42.                                                                                                         .includes('xls') || nameKZ.includes(
  43.                                                                                                                 'pdf') || nameKZ.includes('png') ||
  44.                                                                                                         nameKZ.includes('jpg') || nameKZ
  45.                                                                                                         .includes('jpeg') || nameKZ.includes(
  46.                                                                                                                 'bmp')) {} else {
  47.                                                                                                         uni.showToast({
  48.                                                                                                                 title: '附件只能上传图片、pdf、word、excel',
  49.                                                                                                                 icon: 'none'
  50.                                                                                                         });
  51.                                                                                                         return
  52.                                                                                                 }
  53.                                                                                                 let tempUrl = ''
  54.                                                                                                 let tempName = ''
  55.                                                                                                 //逐个上传   单张图片上传
  56.                                                                                                 uni.showLoading({
  57.                                                                                                         title: '附件上传中...'
  58.                                                                                                 });
  59.                                                                                                 this.$Api.uploadFile([item6.path], 390000,
  60.                                                                                                         res => {
  61.                                                                                                                 console.log(res)
  62.                                                                                                                 tempUrl = this.$Api.url +
  63.                                                                                                                         '/get_uploads?sys=602&url=' +
  64.                                                                                                                         res[0].file_path
  65.                                                                                                                 tempName = res[0].file_name
  66.                                                                                                                 console.log(tempUrl)
  67.                                                                                                                 let data = {
  68.                                                                                                                         url: tempUrl,
  69.                                                                                                                         file_url: res[0].file_path,
  70.                                                                                                                         file_name: tempName,
  71.                                                                                                                         file_size: (item6
  72.                                                                                                                                         .size / 1024)
  73.                                                                                                                                 .toFixed(1) + 'kb',
  74.                                                                                                                         file_ext: temp
  75.                                                                                                                                 .substring(temp
  76.                                                                                                                                         .lastIndexOf(
  77.                                                                                                                                                 '.') + 1,
  78.                                                                                                                                         temp.length)
  79.                                                                                                                 }
  80.                                                                                                                 this.arrs_otherProfile.push(
  81.                                                                                                                         data)
  82.                                                                                                                 console.log(this
  83.                                                                                                                         .arrs_otherProfile)
  84.                                                                                                                 this.$forceUpdate()
  85.                                                                                                                 uni.hideLoading();
  86.                                                                                                         }, e => {
  87.                                                                                                                 uni.hideLoading();
  88.                                                                                                         })
  89.                                                                                         })
  90.                                                                                 }
  91.                                                                         }
  92.                                                                 });
  93.                                                         } else if (res.tapIndex == 1) {
  94.                                                                 var _this = this
  95.                                                                 // 选择文件
  96.                                                                 vue.$store.commit('setIsHideByChooseFile', true)
  97.                                                                 chooseFile(url => {
  98.                                                                         console.log(url)
  99.                                                                         // /storage/emulated/0/DCIM/Screenshots/IMG_20221105_151817.jpg
  100.                                                                         //获取扩展名
  101.                                                                         var nameKZ = url.substring(url.lastIndexOf(".") +
  102.                                                                                 1, url.length);
  103.                                                                         console.log(nameKZ);
  104.                                                                         if (nameKZ.includes('doc') || nameKZ.includes(
  105.                                                                                         'xls') || nameKZ.includes('pdf') || nameKZ
  106.                                                                                 .includes('png') || nameKZ.includes('jpg') ||
  107.                                                                                 nameKZ.includes('jpeg') || nameKZ.includes(
  108.                                                                                         'bmp')) {
  109.                                                                         } else {
  110.                                                                                 uni.showToast({
  111.                                                                                         title: '附件只能上传图片、pdf、word、excel',
  112.                                                                                         icon: 'none'
  113.                                                                                 });
  114.                                                                                 return
  115.                                                                         }
  116.                                                                         //获取文件名
  117.                                                                         var name = url.substring(url.lastIndexOf("/") + 1,
  118.                                                                                 url.length);
  119.                                                                         console.log(name);
  120.                                                                         uni.showLoading({
  121.                                                                                 title: '附件上传中...'
  122.                                                                         });
  123.                                                                         _this.$Api.uploadFile([url], 390000, res => {
  124.                                                                                 console.log(res)
  125.                                                                                 let file_path = _this.$Api.url +
  126.                                                                                         '/get_uploads?sys=602&url=' + res[
  127.                                                                                                 0].file_path
  128.                                                                                 let data = {
  129.                                                                                         url: file_path,
  130.                                                                                         file_url: res[0].file_path,
  131.                                                                                         file_name: name,
  132.                                                                                         file_ext: name.substring(name
  133.                                                                                                 .lastIndexOf('.') + 1,
  134.                                                                                                 name.length)
  135.                                                                                 }
  136.                                                                                 _this.arrs_otherProfile.push(data)
  137.                                                                                 console.log(_this.arrs_otherProfile)
  138.                                                                                 uni.hideLoading();
  139.                                                                         }, e => {
  140.                                                                                 console.log(e)
  141.                                                                                 uni.hideLoading();
  142.                                                                         })
  143.                                                                 })
  144.                                                         }
  145.                                                 }
  146.                                         })
  147.                                 } else if (device == 'ios') {
  148.                                         vue.$store.commit('setIsHideByChooseFile', true)
  149.                                         // 从相册中选
  150.                                         uni.chooseImage({
  151.                                                 count: 9,
  152.                                                 sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  153.                                                 sourceType: ['album'], //从相册选择
  154.                                                 success: (image) => {
  155.                                                         console.log(image)
  156.                                                         var temp = ''
  157.                                                         if (image.tempFiles && image.tempFiles.length > 0) {
  158.                                                                 image.tempFiles.forEach(item6 => {
  159.                                                                         // #ifdef H5
  160.                                                                         temp = item6.name
  161.                                                                         // #endif
  162.                                                                         // #ifdef APP-PLUS
  163.                                                                         temp = item6.path.substring(item6.path.lastIndexOf('/') + 1, item6
  164.                                                                                 .path.length)
  165.                                                                         // #endif
  166.                                                                         //H5
  167.                                                                         console.log(temp)
  168.                                                                         //获取扩展名
  169.                                                                         var nameKZ = temp.substring(temp.lastIndexOf(".") + 1, temp
  170.                                                                         .length);
  171.                                                                         console.log(nameKZ);
  172.                                                                         if (nameKZ.includes('doc') || nameKZ.includes('xls') || nameKZ
  173.                                                                                 .includes('pdf') || nameKZ.includes('png') || nameKZ.includes(
  174.                                                                                         'jpg') || nameKZ.includes('jpeg') || nameKZ.includes('bmp')||
  175.                                                                                         nameKZ.includes('BMP') || nameKZ.includes('JPEG') ||nameKZ.includes('JPG') ||nameKZ.includes('PNG')
  176.                                                                                 ) {} else {
  177.                                                                                 uni.showToast({
  178.                                                                                         title: '附件只能上传图片、pdf、word、excel',
  179.                                                                                         icon: 'none'
  180.                                                                                 });
  181.                                                                                 return
  182.                                                                         }
  183.                                                                         let tempUrl = ''
  184.                                                                         let tempName = ''
  185.                                                                         //逐个上传   单张图片上传
  186.                                                                         uni.showLoading({
  187.                                                                                 title: '附件上传中...'
  188.                                                                         });
  189.                                                                         this.$Api.uploadFile([item6.path], 390000, res => {
  190.                                                                                 console.log(res)
  191.                                                                                 tempUrl = this.$Api.url + '/get_uploads?sys=602&url=' +
  192.                                                                                         res[0].file_path
  193.                                                                                 tempName = res[0].file_name
  194.                                                                                 console.log(tempUrl)
  195.                                                                                 let data = {
  196.                                                                                         url: tempUrl,
  197.                                                                                         file_url: res[0].file_path,
  198.                                                                                         file_name: tempName,
  199.                                                                                         file_size: (item6.size / 1024).toFixed(1) +
  200.                                                                                                 'kb',
  201.                                                                                         file_ext: temp.substring(temp.lastIndexOf(
  202.                                                                                                 '.') + 1, temp.length)
  203.                                                                                 }
  204.                                                                                 this.arrs_otherProfile.push(data)
  205.                                                                                 console.log(this.arrs_otherProfile)
  206.                                                                                 this.$forceUpdate()
  207.                                                                                 uni.hideLoading();
  208.                                                                         }, e => {
  209.                                                                                 // errorBack && errorBack(e)
  210.                                                                                 uni.hideLoading();
  211.                                                                         })
  212.                                                                 })
  213.                                                         }
  214.                                                 }
  215.                                         });
  216.                                 }
  217.                         },
复制代码

Androd 选择附件的文件

  1. var chooseFile = function(callback, acceptType) {
  2.    
  3.     var CODE_REQUEST = 1000;
  4.     var main = plus.android.runtimeMainActivity();
  5.     if(plus.os.name == 'Android') {
  6.         console.log("666");
  7.         var Intent = plus.android.importClass('android.content.Intent');
  8.         var intent = new Intent(Intent.ACTION_GET_CONTENT);
  9.         intent.addCategory(Intent.CATEGORY_OPENABLE);
  10.         if(acceptType) {
  11.             intent.setType(acceptType);
  12.         } else {
  13.             intent.setType("*/*");
  14.         }
  15.         main.onActivityResult = (requestCode, resultCode, data)=>{
  16.                         console.log(data)
  17.             if(requestCode == CODE_REQUEST) {
  18.                 const uri = data.getData();
  19.                                
  20.                 plus.android.importClass(uri);
  21.                 const Build = plus.android.importClass('android.os.Build');
  22.                 const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
  23.                                 console.log(Build.VERSION.SDK_INT)
  24.                                 console.log(Build.VERSION_CODES.KITKAT)
  25.                 const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
  26.                                 console.log(uri.getScheme())
  27.                 if(isKitKat && DocumentsContract.isDocumentUri(main, uri)) {
  28.                                         console.log(uri.getAuthority())
  29.                     if("com.android.externalstorage.documents" == uri.getAuthority()) {
  30.                         console.log("6666");
  31.                         var docId = DocumentsContract.getDocumentId(uri);
  32.                         var split = docId.split(":");
  33.                         var type = split[0];
  34.                         console.log(type);
  35.                         if("primary" == type) {
  36.                             var Environment = plus.android.importClass('android.os.Environment');
  37.                                                         console.log(Environment.getExternalStorageDirectory() + "/" + split[1]);
  38.                             callback(Environment.getExternalStorageDirectory() + "/" + split[1]);
  39.                         } else {
  40.                             var System = plus.android.importClass('java.lang.System');
  41.                             var sdPath = System.getenv("SECONDARY_STORAGE");
  42.                                                         console.log(sdPath)
  43.                             if(sdPath) {
  44.                                 callback(sdPath + "/" + split[1]);
  45.                             }
  46.                         }
  47.                     }
  48.                     else if("com.android.providers.downloads.documents" == uri.getAuthority()) {
  49.                                                 console.log("7777");
  50.                         var id = DocumentsContract.getDocumentId(uri);
  51.                         var ContentUris = plus.android.importClass('android.content.ContentUris');
  52.                         var contentUri = ContentUris.withAppendedId(
  53.                         Uri.parse("content://downloads/public_downloads"), id);
  54.                         callback(getDataColumn(main, contentUri, null, null));
  55.                     }
  56.                     else if("com.android.providers.media.documents" == uri.getAuthority()) {
  57.                                                 console.log("8888");
  58.                         var docId = DocumentsContract.getDocumentId(uri);
  59.                         var split = docId.split(":");
  60.                         console.log(split);
  61.                         var type = split[0];
  62.                         console.log(type);
  63.                         var MediaStore = plus.android.importClass('android.provider.MediaStore');
  64.                         if("image" == type) {
  65.                             contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  66.                         } else if("video" == type) {
  67.                             contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
  68.                         } else if("audio" == type) {
  69.                             contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  70.                         }else{
  71.                              contentUri = MediaStore.Files.getContentUri("external");
  72.                         }
  73.                         console.log(contentUri);
  74.                         var selection = "_id=?";
  75.                         var selectionArgs = new Array();
  76.                         selectionArgs[0] = split[1];
  77.                         callback(getDataColumn(main, contentUri, selection, selectionArgs));
  78.                     }
  79.                 }
  80.                 else if("content" == uri.getScheme()) {
  81.                                         console.log("9999");
  82.                                         console.log("9999",main);
  83.                                         console.log("9999",uri);
  84.                     callback(getDataColumn(main, uri, null, null));
  85.                 }
  86.                 else if("file" == uri.getScheme()) {
  87.                                         console.log("0000");
  88.                                         console.log(uri.getPath());
  89.                     callback(uri.getPath());
  90.                 }
  91.             }
  92.         }
  93.         main.startActivityForResult(intent, CODE_REQUEST);
  94.     }
  95. }
  96. function getDataColumn(main, uri, selection, selectionArgs) {
  97.         plus.android.importClass(main.getContentResolver());
  98.         let cursor = main.getContentResolver().query(uri, ['_data'], selection, selectionArgs,
  99.         null);
  100.         plus.android.importClass(cursor);
  101.         if(cursor != null && cursor.moveToFirst()) {
  102.         var column_index = cursor.getColumnIndexOrThrow('_data');
  103.         var result = cursor.getString(column_index);
  104.                 console.log(result);
  105.         cursor.close();
  106.         return result;
  107.         }
  108.         return null;
  109. }
  110. export default chooseFile
复制代码

 附送250套精选项目源码

源码截图

源码获取:关注公众号「码农园区」,回复 【源码】,即可获取全套源码下载链接





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

金歌

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表