uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码),Uniapp附件上传与在线预览功能(含图片、PDF、Word、Excel),Android与iOS支持,附送微信小程序源码合集(共250套精选)

马肤

温馨提示:这篇文章已超过374天没有更新,请注意相关的内容是否还可用!

摘要:本内容介绍了使用uniapp进行附件(包括图片、PDF、Word、Excel)的上传和在线预览功能,特别针对Android和iOS平台。附送250套精选微信小程序源码。该摘要旨在提供一项便捷的文件处理解决方案,支持多种文件格式,适用于移动应用程序开发,方便用户上传和查看各类附件。

一、PDF预览

1、下载PDF预览相关文件

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

    uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码),Uniapp附件上传与在线预览功能(含图片、PDF、Word、Excel),Android与iOS支持,附送微信小程序源码合集(共250套精选) 第1张

    2、使用步骤

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

      uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码),Uniapp附件上传与在线预览功能(含图片、PDF、Word、Excel),Android与iOS支持,附送微信小程序源码合集(共250套精选) 第2张

      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套精选项目源码

      源码截图
      uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码),Uniapp附件上传与在线预览功能(含图片、PDF、Word、Excel),Android与iOS支持,附送微信小程序源码合集(共250套精选) 第3张

      源码获取:关注公众号「码农园区」,回复 【源码】,即可获取全套源码下载链接
      uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码),Uniapp附件上传与在线预览功能(含图片、PDF、Word、Excel),Android与iOS支持,附送微信小程序源码合集(共250套精选) 第4张


0
收藏0
文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。

相关阅读

  • 【研发日记】Matlab/Simulink自动生成代码(二)——五种选择结构实现方法,Matlab/Simulink自动生成代码的五种选择结构实现方法(二),Matlab/Simulink自动生成代码的五种选择结构实现方法详解(二)
  • 超级好用的C++实用库之跨平台实用方法,跨平台实用方法的C++实用库超好用指南,C++跨平台实用库使用指南,超好用实用方法集合,C++跨平台实用库超好用指南,方法与技巧集合
  • 【动态规划】斐波那契数列模型(C++),斐波那契数列模型(C++实现与动态规划解析),斐波那契数列模型解析与C++实现(动态规划)
  • 【C++】,string类底层的模拟实现,C++中string类的模拟底层实现探究
  • uniapp 小程序实现微信授权登录(前端和后端),Uniapp小程序实现微信授权登录全流程(前端后端全攻略),Uniapp小程序微信授权登录全流程攻略,前端后端全指南
  • Vue脚手架的安装(保姆级教程),Vue脚手架保姆级安装教程,Vue脚手架保姆级安装指南,Vue脚手架保姆级安装指南,从零开始教你如何安装Vue脚手架
  • 如何在树莓派 Raspberry Pi中本地部署一个web站点并实现无公网IP远程访问,树莓派上本地部署Web站点及无公网IP远程访问指南,树莓派部署Web站点及无公网IP远程访问指南,本地部署与远程访问实践,树莓派部署Web站点及无公网IP远程访问实践指南,树莓派部署Web站点及无公网IP远程访问实践指南,本地部署与远程访问详解,树莓派部署Web站点及无公网IP远程访问实践详解,本地部署与远程访问指南,树莓派部署Web站点及无公网IP远程访问实践详解,本地部署与远程访问指南。
  • vue2技术栈实现AI问答机器人功能(流式与非流式两种接口方法),Vue2技术栈实现AI问答机器人功能,流式与非流式接口方法探究,Vue2技术栈实现AI问答机器人功能,流式与非流式接口方法详解
  • 发表评论

    快捷回复:表情:
    评论列表 (暂无评论,0人围观)

    还没有评论,来说两句吧...

    目录[+]

    取消
    微信二维码
    微信二维码
    支付宝二维码