金歌 发表于 2024-6-26 05:20:06

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

一、PDF预览

1、下载PDF预览相关文件



[*]下载地址
[*]解压后结果:
https://img-blog.csdnimg.cn/direct/663799cec6a64d1c9952d703499294a9.png
2、使用步骤



[*]在  static  文件夹下新建  pdf  文件夹,将解压文件放进  pdf  文件夹下(看网上很多博主把文件夹放在根目次里,我反正之前试到最后始终无法打开预览请求的PDF文件!  避坑  :放在  static 文件夹下就没问题了)
[*]如图所示:
https://img-blog.csdnimg.cn/direct/c267a1b7134d49878032290baf3bb088.png
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

<template>
        <view style="width: 100%;" >
                <web-view:src="webViewUrl"></web-view>
        </view>
</template>

<script>
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}`
        }
}
</script>

<style>
</style> 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
                                        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(, 390000,
                                                                                                        res => {
                                                                                                                console.log(res)
                                                                                                                tempUrl = this.$Api.url +
                                                                                                                        '/get_uploads?sys=602&url=' +
                                                                                                                        res.file_path
                                                                                                                tempName = res.file_name
                                                                                                                console.log(tempUrl)

                                                                                                                let data = {
                                                                                                                        url: tempUrl,
                                                                                                                        file_url: res.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(, 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.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(, 390000, res => {
                                                                                console.log(res)
                                                                                tempUrl = this.$Api.url + '/get_uploads?sys=602&url=' +
                                                                                        res.file_path
                                                                                tempName = res.file_name
                                                                                console.log(tempUrl)

                                                                                let data = {
                                                                                        url: tempUrl,
                                                                                        file_url: res.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;
                        console.log(type);
                        if("primary" == type) {
                            var Environment = plus.android.importClass('android.os.Environment');
                                                        console.log(Environment.getExternalStorageDirectory() + "/" + split);
                            callback(Environment.getExternalStorageDirectory() + "/" + split);
                        } else {
                            var System = plus.android.importClass('java.lang.System');
                            var sdPath = System.getenv("SECONDARY_STORAGE");
                                                        console.log(sdPath)
                            if(sdPath) {
                              callback(sdPath + "/" + split);
                            }
                        }
                  }
                  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;
                        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 = split;

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

源码截图
https://img-blog.csdnimg.cn/direct/4e2c0287ce6f47788bd67676fd336148.png
源码获取:关注公众号「码农园区」,回复 【源码】,即可获取全套源码下载链接
https://img-blog.csdnimg.cn/direct/6740df33862540d2a02fe3dd101d5e5a.jpeg




免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: uniapp 附件(图片、pdf、word、excle)上传、在线预览 (Android、Ios)(