【uni-app】微信小程序下载预览文件并监听下载进度
一、效果展示
微信小程序文件下载
二、安装微信SDK
npm i jweixin-module
二、获取下载文件文件名称/文件类型(JS文件)
whatFileType(url, name) {
let p = url.split('?')[1];
let keyValue = p.split('&');
let obj = {};
for (let i = 0; i < keyValue.length; i++) {
let item = keyValue[i].split('=');
let key = item[0];
let value = item[1];
obj[key] = value;
}
let sr = obj.name.lastIndexOf('.')
let fileType = obj.name.substr((sr + 1))
return (fileType)
},
FileName(url, name) {
let p = url.split('?')[1];
let keyValue = p.split('&');
let obj = {};
for (let i = 0; i < keyValue.length; i++) {
let item = keyValue[i].split('=');
let key = item[0];
let value = item[1];
obj[key] = value;
}
return obj.name;
}
三、全局引用JS文件
import download_file from "@/common/js/download_file.js"
Vue.prototype.$download_file = download_file;
四、清理该小程序下已保存的本地缓存文件列表
wx.getFileSystemManager().getSavedFileList({
success(res) {
res.fileList.forEach((val, key) => {
//删除存储数据
wx.removeSavedFile({
filePath: val.filePath
});
})
}
})
五、下载并监听进度,完成后自动预览
//下载文件资源到本地
let downloadTask = wx.downloadFile({
url: url,
filePath: wx.env.USER_DATA_PATH + "/" + fileName,
method: 'GET',
success: function(res) {
if (fileTypes.includes(fileType)) {
self.preview_filePath = res.filePath;
//预览文件
wx.openDocument({
filePath: res.filePath,
showMenu: true,
flieType: fileType,
success: function(res) {
wx.hideLoading();
self.showBtn = 2;
},
fail: function(err) {
wx.hideLoading();
self.showBtn = 2;
},
});
} else if (imageTypes.includes(fileType)) {
wx.hideLoading();
//预览图片
wx.previewImage({
showmenu: true,
current: res.filePath, // 当前显示图片的http链接
urls: [res.filePath] // 需要预览的图片http链接列表
})
} else {
wx.hideLoading()
wx.showModal({
title: '提示',
content: "文件类型不支持预览,请保存到本地后再进行操作!",
showCancel: false
})
}
},
fail: function(err) {
wx.hideLoading()
wx.showToast({
title: "下载超时,请重新下载",
icon: 'none'
})
self.showBtn = 0;
self.percent = 0;
}
})
//监听下载变化事件
downloadTask.onProgressUpdate((res) => {
self.percent = res.totalBytesWritten / 10000;
});
六、全部代码
<template>
<view class="content" :style="'height:' + windowHeight + 'px;width:' + windowWidth + 'px'">
<view class="data-body">
<view>
<u--text :text="fileInfo.name" align="center" size="20" bold></u--text>
</view>
<view style="width: 100%;display: flex;justify-content: center;flex-direction: column;">
<view v-if="showBtn == 0" style="width: 100%;height: 50px;display: flex;justify-content: center;">
<view style="width: 300rpx;height: 100%;">
<u-button type="success" @click="download">接收文件</u-button>
</view>
</view>
<view v-else-if="showBtn == 2" style="width: 100%;height: 50px;display: flex;justify-content: center;">
<view style="width: 300rpx;height: 100%;">
<u-button type="success" @click="preview">重新预览</u-button>
</view>
</view>
<view v-else="showBtn == 1" style="width: 100%;display: flex;justify-content: center;">
<l-circularProgress :isBgShow="false" :lineWidth="10" :boxWidth="100" :boxHeight="100"
progressColor="#19be6b" fontColor="#19be6b" gradualColor="#19be6b"
:percent="percent"></l-circularProgress>
</view>
<view style="width: 100%;height: 80px;"></view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
windowHeight: '100%',
windowWidth: '100%',
fileInfo: {},
fileType: "",
percent: 0,
showBtn: 0,
preview_filePath: '',
};
},
created() {
uni.getSystemInfo({
success: (res) => {
this.windowHeight = res.windowHeight;
this.windowWidth = res.windowWidth;
}
});
if (JSON.stringify(this.$store.state.fileInfo) != "{}") {
this.fileInfo = this.$store.state.fileInfo;
this.fileType = this.$download_file.whatFileType(this.$store.state.fileInfo.link, 'name');
} else {
uni.navigateBack();
}
},
onLoad(options) {
},
methods: {
download() {
this.showBtn = 1;
this.downloadFile(this.fileInfo.link);
},
downloadFile(url) {
let self = this;
let fileTypes = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
let imageTypes = ["jpg", "jpeg", "png"]
let fileType = this.$download_file.whatFileType(url, "name");
let fileName = this.$download_file.FileName(url, "name");
// #ifdef MP-WEIXIN
wx.getFileSystemManager().getSavedFileList({
success(res) {
res.fileList.forEach((val, key) => {
// 删除存储的垃圾数据
wx.removeSavedFile({
filePath: val.filePath
});
})
}
})
let downloadTask = wx.downloadFile({
url: url,
filePath: wx.env.USER_DATA_PATH + "/" + fileName,
method: 'GET',
success: function(res) {
if (fileTypes.includes(fileType)) {
self.preview_filePath = res.filePath;
wx.openDocument({
filePath: res.filePath,
showMenu: true,
flieType: fileType,
success: function(res) {
wx.hideLoading();
self.showBtn = 2;
},
fail: function(err) {
wx.hideLoading();
self.showBtn = 2;
},
});
} else if (imageTypes.includes(fileType)) {
wx.hideLoading()
wx.previewImage({
showmenu: true,
current: res.filePath, // 当前显示图片的http链接
urls: [res.filePath] // 需要预览的图片http链接列表
})
} else {
wx.hideLoading()
wx.showModal({
title: '提示',
content: "文件类型不支持预览,请保存到本地后再进行操作!",
showCancel: false
})
}
},
fail: function(err) {
wx.hideLoading()
wx.showToast({
title: "下载超时",
icon: 'none'
})
self.showBtn = 0;
self.percent = 0;
}
})
downloadTask.onProgressUpdate((res) => {
self.percent = res.totalBytesWritten / 10000
});
// #endif
},
preview() {
let self = this;
wx.openDocument({
filePath: this.preview_filePath,
showMenu: true,
flieType: this.fileType,
success: function(res) {
wx.hideLoading();
self.showBtn = 2;
},
fail: function(err) {
wx.hideLoading();
self.showBtn = 2;
}
});
}
}
}
</script>
<style lang="less" scoped>
.content {
background-color: #FFFFFF;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex-grow: 1;
overflow-x: hidden;
.data-body {
width: calc(100% - 100rpx);
height: calc(100% - 300rpx);
display: flex;
flex-direction: column;
justify-content: space-between;
}
}
</style>