uniapp附件预览并保存到手机本地(图片视频类和非图片视频类)

<view class="card-content" v-for="item in cardData.files" :key="item.id" @click="downLoad(item)">
  <text>{{item.fileName}}</text>
</view>

 

//下载
downLoad(item) {
    console.log(item.filePath, 390)  
//http://172.17.30.73:9006/spang-safety/file/temp/20220815/1660493727470567.mp4
var e = item.filePath var imgType = ['png', 'jpg', 'jpeg'] var audioType = ['mp4', 'MP4'] let _this = this //下载地址 this.downloadUlr = e //获取地址后缀 this.suffix = e.split('.')[e.split('.').length - 1] console.log(this.suffix) //判断是否为(图片或视频) if (imgType.includes(this.suffix) || audioType.includes(this.suffix)) { const downloadTask = uni.downloadFile({ url: e, //下载地址接口返回 success: (data) => { if (data.statusCode === 200) { if (audioType.includes(this.suffix)) { //视频 //保存视频到相册 uni.saveVideoToPhotosAlbum({ filePath: data.tempFilePath, success: function() { uni.showToast({ title: '保存成功', incon: 'none', duration: 2000, mask: true }) }, fail: function() { uni.showToast({ title: '保存失败', incon: 'none' }) } }) } else { //图片 //保存图片到手机相册 uni.saveImageToPhotosAlbum({ filePath: data.tempFilePath, success: function() { uni.showToast({ title: '保存成功', icon: 'none', duration: 2000, mask: true }) //图片保存成功后自动预览图片 uni.previewImage({ urls: [e], longPressActions: { success: function(data) { console.log(data) }, fail: function(err) { console.log(err.errMsg); } } }); }, fail: function() { uni.showToast({ title: '保存失败', icon: 'none' }) } }) } } else { uni.showToast({ title: '下载失败', icon: 'none' }) } }, fail: (err) => { uni.showToast({ icon: 'none', mask: true, title: '下载失败', }); }, }); }else{ //下载文件为非图片和视频文件 let _this = this const downloadTaskt = uni.downloadFile({ url:e,//下载地址接口返回 success:(data)=>{ uni.hideLoading() if(data.statusCode === 200){ var sFilePath = data.tempFilePath var sFileName = _this.downloadUlr.split('/')[_this.downloadUlr.split('/').length - 1]; //原来的文件名 console.log(sFileName,476) //文件保存到本地 uni.saveFile({ tempFilePath: data.tempFilePath, //临时路径 success: function(res) { var savedFilePath = res.savedFilePath; let osname = plus.os.name; //ios手机直接打开文件,手动存储文件到手机,Android手机从根目录创建文件夹,保存文件并改名 if (osname == 'Android') { uni.showToast({ icon: 'none', mask: true, title: '保存成功', duration: 1000, }); _this.fSetFileName(res.savedFilePath, sFilePath); } setTimeout(() => { //打开文档查看 uni.openDocument({ filePath: res.savedFilePath, success: function(res) { // console.log('打开文档成功'); } }); }, 1000)}, fail: function(res) { uni.showToast({ icon: "none", mask: true, title: '下载失败' }) } }); } } }) } }, // 给下载的文件重命名 fSetFileName(sFilePath, sFileName) { var sFileName = sFileName.split('/')[sFileName.split('/').length - 1]; //原来的文件名 var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1); //saveFile API保存的本地地址 var url = this.downloadUlr; //下载地址 // 'url下载地址(和上面的一样)' let dtask = plus.downloader.createDownload(url, { filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹,把文件存储进去,并更改会原名 }, (d, status) => { if (status == 200) { let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename); } else { //下载失败 plus.downloader.clear(); //清除下载任务 } }) dtask.start(); },

 

       //预览
            previewData(data) {
                this.fileUrl = this.basicImgUrl + data
                var fileType = ['pptx', 'ppt', 'docx', 'doc', 'xlsx', 'xls', 'pdf']
                var imgType = ['png', 'jpg', 'jpeg']
                var audioType = ['mp4']
                var typeName = data.split('.')[1]
                console.log(typeName, 259)
                if (fileType.indexOf(typeName) !== -1) { //文档类文件
                    uni.showLoading({
                        title: '加载中',
                        mask: true
                    })
                    // this.showPreview = true
                    uni.downloadFile({
                        url: this.fileUrl,
                        success: function(res) {
                            console.log('downloadFile ==> ', res)
                            uni.hideLoading();
                            var filePath = res.tempFilePath;
                            uni.showLoading({
                                title: '正在打开',
                                mask: true
                            })
                            uni.openDocument({
                                filePath: filePath,
                                fileType: typeName, // 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx 
                                showMenu: true, // 允许出现分享功能
                                success: res => {
                                    uni.hideLoading();
                                    console.log('打开文档成功', res);
                                },
                                fail: openError => {
                                    uni.hideLoading();
                                    console.log('fail:' + JSON.stringify(openError));
                                }
                            });
                        },
                        fail: function(err) {
                            uni.hideLoading();
                            console.log('fail:' + JSON.stringify(err));
                        }
                    });

                }
                if (imgType.indexOf(typeName) !== -1) { //图片类文件
                    uni.previewImage({
                        urls: [this.fileUrl],
                        longPressActions: {
                            success: function(data) {
                                console.log(data)
                            },
                            fail: function(err) {
                                console.log(err.errMsg);
                            }
                        }
                    });
                }
                if (audioType.indexOf(typeName) !== -1) {
                    console.log(313)
                    const innerAudioContext = uni.createInnerAudioContext();
                    innerAudioContext.autoplay = true;
                    innerAudioContext.src = this.fileUrl
                    innerAudioContext.onPlay(() => {
                        console.log('开始播放');
                    });
                    innerAudioContext.onError((res) => {
                        console.log(res.errMsg);
                        console.log(res.errCode);
                    });

                }
            },
       //附件下载
            downLoad(item) {
                item.download = true
                var e = this.basicImgUrl + item.filePath
                let _this = this;
                //下载地址
                this.downloadUlr = e;
                //获取地址后缀
                this.suffix = e.split(".")[e.split(".").length - 1];
                
                console.log(e.substring(e.length - 3))
                //判断是否为(图片或视频)
                if (e.substring(e.length - 3) == "MP4" || e.substring(e.length - 3) == "mp4" || e.substring(e.length -
                        3) == "jpg" || e.substring(e.length - 3) == "png") {
                    const downloadTask = uni.downloadFile({
                        url: e,
                        success: res => {
                            if (res.statusCode === 200) {
                                if (res.tempFilePath.substring(res.tempFilePath.length - 3) == "mp4" || res
                                    .tempFilePath.substring(res.tempFilePath.length - 3) == "MP4") { //视频
                                    //保存视频到相册
                                    uni.saveVideoToPhotosAlbum({
                                        filePath: res.tempFilePath,
                                        success: function() {
                                            uni.showToast({
                                                title: '下载成功',
                                                icon: 'none',
                                                duration: 2000,
                                                mask: true
                                            });
                                        },
                                        fail: function() {
                                            item.progress = 0;
                                            uni.showToast({
                                                title: '保存失败',
                                                icon: 'none'
                                            });
                                        }
                                    });
                                } else { //图片
                                    // 图片保存到手机相册
                                    uni.saveImageToPhotosAlbum({
                                        filePath: res.tempFilePath,
                                        success: function() {
                                            uni.showToast({
                                                title: '下载成功',
                                                icon: 'none',
                                                duration: 2000,
                                                mask: true
                                            });
                                        },
                                        fail: function() {
                                            item.progress = 0;
                                            uni.showToast({
                                                title: '保存失败',
                                                icon: 'none'
                                            });
                                        }
                                    });
                                }
                            } else {
                                uni.showToast({
                                    title: '下载失败',
                                    icon: "none"
                                })
                            }
                        },
                        fail: (err) => {
                            item.progress = 0;
                            uni.showToast({
                                icon: "none",
                                mask: true,
                                title: '下载失败'
                            })
                        }
                    });
                    downloadTask.onProgressUpdate((res) => {
                        console.log('下载进度' + res.progress);
                        this.$set(item, 'progress', res.progress)
                        this.$set(item, 'downloadPercent', res.progress)
                        // console.log('已经下载的数据长度' + res.totalBytesWritten);
                        // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
                        // 满足测试条件,取消下载任务。
                        if (res.progress === 100) {
                            // downloadTask.abort();
                            this.$set(item, 'download', false)
                        }
                    });
                } else {
                    //下载文件为非图片和视频的文件
                    let _this = this;
                    const downloadTaskt = uni.downloadFile({
                        url: e, //下载地址接口返回
                        success: (data) => {
                            uni.hideLoading()
                            if (data.statusCode === 200) {
                                var sFilePath = data.tempFilePath
                                var sFileName = _this.downloadUlr.split('/')[_this.downloadUlr.split('/')
                                    .length - 1]; //原来的文件名

                                //#ifdef APP-PLUS
                                //文件保存到本地
                                uni.saveFile({
                                    tempFilePath: data.tempFilePath, //临时路径
                                    success: function(res) {
                                        var savedFilePath = res.savedFilePath;
                                        let osname = plus.os.name;
                                        //ios手机直接打开文件,手动存储文件到手机,Android手机从根目录创建文件夹,保存文件并改名
                                        if (osname == 'Android') {
                                            uni.showToast({
                                                icon: 'none',
                                                mask: true,
                                                title: '下载成功',
                                                duration: 1000,
                                            });
                                            _this.fSetFileName(res.savedFilePath, sFilePath);
                                        }
                                        setTimeout(() => {
                                            //打开文档查看
                                            uni.openDocument({
                                                filePath: res.savedFilePath,
                                                success: function(res) {
                                                    // console.log("成功打开文件")
                                                },
                                                fail() {
                                                    // console.log("打开文件失败")
                                                }
                                            })
                                        }, 1000)
                                    },
                                    fail: function(res) {
                                        item.progress = 0;
                                        uni.showToast({
                                            icon: "none",
                                            mask: true,
                                            title: '下载失败'
                                        })
                                    }
                                });
                                //#endif

                            } else {
                                item.progress = 0;
                                uni.showToast({
                                    icon: "none",
                                    mask: true,
                                    title: "下载失败"
                                })
                            }
                        },
                        fail: (err) => {
                            item.progress = 0;
                            uni.showToast({
                                icon: "none",
                                mask: true,
                                title: "下载失败"
                            })
                        }
                    })
                    downloadTaskt.onProgressUpdate((res) => {
                        console.log('下载进度' + res.progress);
                        this.$set(item, 'progress', res.progress)
                        this.$set(item, 'downloadPercent', res.progress)
                        // console.log('已经下载的数据长度' + res.totalBytesWritten);
                        // console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
                        // 满足测试条件,取消下载任务。
                        if (res.progress === 100) {
                            // downloadTask.abort();
                            this.$set(item, 'download', false)
                        }
                    });
                }
            },
            // 给下载的文件重命名
            fSetFileName(sFilePath, sFileName) {
                var sFileName = sFileName.split('/')[sFileName.split('/').length - 1]; //原来的文件名

                var aFileUrl = sFilePath.split('/').splice(0, sFilePath.split('/').length - 1); //saveFile API保存的本地地址

                var url = this.downloadUlr; //下载地址
                // 'url下载地址(和上面的一样)'
                let dtask = plus.downloader.createDownload(url, {
                        filename: "file://storage/emulated/0/AAA/" + sFileName //在手机存储更目录创建一个叫AAA的文件夹,把文件存储进去,并更改会原名
                    },
                    (d, status) => {
                        if (status == 200) {
                            let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);

                        } else {
                            //下载失败
                            plus.downloader.clear(); //清除下载任务
                        }
                    })
                dtask.start();
            },

 

 

https://blog.csdn.net/fbqgdxw/article/details/124293782

https://blog.csdn.net/sunhuaqiang1/article/details/125528229

https://blog.csdn.net/jiongxian1/article/details/124702745

posted @ 2022-08-12 10:41  奔向太阳的向日葵  阅读(2353)  评论(0编辑  收藏  举报