当前位置:   article > 正文

uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(附送250套精选微信小程序源码)_uniapp 上传excel文件

uniapp 上传excel文件

一、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. },

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

 附送250套精选项目源码

源码截图

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/571026
推荐阅读
相关标签
  

闽ICP备14008679号