admin管理员组文章数量:1654379
目录
一、视频的下载
二、视频的分享
三、PDF下载和分享
四、完整
五、有可能是坑
一、视频的下载
先使用uni.downloadFile将文件下载到将远程文件下载到小程序内存中,然后使用uni.saveVideoToPhotosAlbum保存到本地系统
注意:使用临时路径,则报错 "saveVideoToPhotosAlbum:fail invalid file type",因此我使用了固定路径,发现可以下载成功
// 下载
async download() {
let that = this
await uni.showLoading({
title: '下载中'
})
let filePath = wx.env.USER_DATA_PATH + '/' + that.word.filename +'.mp4'
//将远程文件下载到小程序内存中
uni.downloadFile({
url: that.word.fileurl,//临时路径
filePath: filePath,//指定路径,去文件管理的微信中查看
success(res) {
// 2 成功下载后而且状态码为200时将视频保存到本地系统
if (res.statusCode === 200) {
uni.saveVideoToPhotosAlbum({
// filePath: res.tempFilePath,
filePath: filePath,
success(res) {
console.log(res, 'success')
},
fail(error) {
console.log(error, 'error')
}
})
uni.hideLoading();
// 提示用户下载成功
uni.showToast({
title: "下载成功",
icon: "success"
});
}
// 如果该资源不可下载或文件格式出错则提示用户
else {
uni.showToast({
title: "资源格式错误,请联系管理员"
});
}
},
fail: (err) => {
// 下载失败提醒
uni.hideLoading();
uni.showToast({
title: "下载失败"
})
}
})
},
二、视频的分享
小程序的分享不能单独分享视频,只能分享页面。所以我就新建了一个分享的页面,然后把视频用列表的形式呈现。就和百度网盘小程序分享的页面差不多。
点击视频后,全屏播放,里面有下载和分享的操作
视频分享的全局js可以看我的另一篇文章:微信小程序分享
分享的新页面new.vue
<template>
<view class="">
<uni-list v-for="(item,index) in list" :key='index'>
<view :border="none" :padding="0" :spacing="0" style="padding:0" :is-shadow="false" :isFull="true">
<view @click="showvideo(item)" class="card-title" style="display: flex;justify-content: space-between;">
<view style="display: flex;">
<uni-badge class="uni-badge-left-margin" :is-dot="true" :text="item.Isupdate?value:''"
absolute="rightTop" size="normal">
<view>
<image v-if="item.fileExt==='.mp4'" class="slot-image"
src="/static/shipin_lvhangyingxiang.png" mode="widthFix">
</image>
<image v-else-if="item.fileExt==='.pdf'" class="slot-image" src="/static/pdfwenjian.png"
mode="widthFix">
</image>
</view>
</uni-badge>
<view class="title-box">
<view class="">{{item.filename}}
</view>
<view class="">{{item.AddTime}}</view>
</view>
</view>
</view>
</view>
</uni-list>
</view>
</template>
<script>
export default {
data() {
return {
list: [],
};
},
onLoad(e) {
let obj = e.item.replace("\"([^\"]*)\"", "$1");
this.list = JSON.parse(obj)
},
methods: {}
}
</script>
<style>
</style>
点击视频后全屏播放的页面appUpdate.vue
<template>
<view class="appUpdateMask">
<view class="appUpdateContent">
<video autoplay controls object-fit="cover" id="myvideo" :src="videoUrl"
@fullscreenchange="screenChange"></video>
<view class="btns">
<button class="btn" @click="download()">
<text>转存到我的手机</text>
</button>
<button class="btn" open-type="share" :data-obj="obj" style="background-color: rgba(102, 102, 102);">
<text>转发给朋友</text>
</button>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
videoUrl: '',
videoPlay: false,
videoContext: '',
obj: []
}
},
onLoad(e) {
this.obj.push(JSON.parse(e.item))
let a = JSON.parse(e.item)
this.videoContext = uni.createVideoContext("myvideo", this); // this这个是实例对象 必传
this.videoUrl = a.fileurl;
this.videoContext.requestFullScreen({
direction: 0
});
this.videoContext.play();
},
methods: {
screenChange(e) {
let fullScreen = e.detail.fullScreen; // 值true为进入全屏,false为退出全屏
// console.log(e, "全屏");
if (!fullScreen) {
//退出全屏
this.videoPlay = false; // 隐藏播放盒子
}
},
// 下载
async download() {
let that = this
wx.getSavedFileList({ // 获取文件列表
success(res) {
// 文件列表超过20个文件,则删除前10个
if (res.fileList.length > 20) {
res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
if (key < 10) {
// 删除存储的垃圾数据
wx.removeSavedFile({
filePath: val.filePath
});
}
})
}
}
})
await uni.showLoading({
title: '下载中'
})
let filePath = wx.env.USER_DATA_PATH + '/' + that.obj[0].filename + '.mp4'
//将远程文件下载到小程序内存中
uni.downloadFile({
url: that.obj[0].fileurl,
// filePath: filePath,
success(res) {
console.log(res)
// 2 成功下载后而且状态码为200时将视频保存到本地系统
if (res.statusCode === 200) {
uni.saveVideoToPhotosAlbum({
// filePath: res.tempFilePath,
filePath: filePath,
success(res) {
// console.log(res, 'success')
uni.hideLoading();
uni.showToast({
title: "下载成功",
icon: "success"
});
// 保存下载记录
this.api.DownloadFile({
FileId: that.obj[0].Id
}).then(res => {
// console.log(res)
})
},
fail(error) {
console.log(error, 'error')
uni.hideLoading();
uni.showToast({
title: "下载失败",
icon: "success"
});
}
})
} else {
// 如果该资源不可下载或文件格式出错则提示用户
uni.showToast({
title: "资源格式错误,请联系管理员"
});
}
},
fail: (err) => {
// 下载失败提醒
uni.hideLoading();
uni.showToast({
title: "下载失败"
})
}
})
},
}
}
</script>
<style lang="scss">
page {
background: transparent;
}
video {
width: 100%;
}
.appUpdateMask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 1);
}
.appUpdateContent {
width: 100vw;
}
.btn {
display: flex;
// flex-direction: row;
align-items: center;
justify-content: space-between;
line-height: 20rpx;
background-color: #1480cd;
border-radius: 50rpx;
text-align: center !important;
padding: 30rpx 60rpx;
width: 45%;
color: #fff;
image {
width: 35rpx;
height: 35rpx;
}
text {
width: 100%;
display: block;
height: 40rpx;
line-height: 40rpx;
font-size: 26rpx
}
}
.btns {
display: flex;
justify-content: space-around;
position: relative;
top: 200rpx;
}
</style>
三、PDF下载和分享
功能点:点击文件进行下载好分享
问题:发现并不能点击列表后直接将文件下载到手机上,而是需要先进行临时下载,下载完成后自动打开文档预览,然后需要用户点击右上角的三点,选择保存到手机还是转发等相应操作。
async download() {
await uni.showLoading({
title: '下载中'
})
uni.downloadFile({
url: this.word.url,
success(res) {
wx.getFileSystemManager().saveFile({
tempFilePath: res.tempFilePath,
// filePath: wx.env.USER_DATA_PATH + '/' + '上传成员.pdf',//自定义文件名
success(res) {
console.log(res)
wx.openDocument({
filePath: res.savedFilePath,
showMenu: true,
success: function(res) {
uni.hideLoading()
uni.showToast({
title: '自动打开文件',
icon: 'none'
})
},
fail(error) {}
})
uni.hideLoading()
uni.showToast({
title: '下载文件成功',
icon: 'none'
})
}
})
},
fail(error) {}
})
}
},
四、完整
<script>
export default{
data(){
return{
loadProgress: 0,//加载index
CustomBar: this.CustomBar,
dltDownLvNew:"",//已下载
dltDownLvAll:"",//总长度
dltDownLvWc:"",//完成率
downloadUlr:"",//下载地址
suffix:"",//文件后缀
}
},
methods:{
clickPeople(e){//点击下载
let _this = this;
//下载地址
this.downloadUlr = e;
//获取地址后缀
this.suffix = e.split(".")[e.split(".").length - 1];
//判断是否为(图片或视频)
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() {
this.loadProgress = 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() {
this.loadProgress = 0;
uni.showToast({
title: '保存失败',
icon: 'none'
});
}
});
}
}else{
uni.showToast({
title:'下载失败',
icon:"none"
})
}
},
fail:(err) => {
this.loadProgress = 0;
uni.showToast({
icon:"none",
mask:true,
title:'下载失败'
})
}
});
downloadTask.onProgressUpdate((res) => {
this.loadProgress = res.progress;
if (this.loadProgress < 100) {
} else {
this.loadProgress = 0;
}
if(res.totalBytesExpectedToWrite < 10485760){
this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
this.dltDownLvWc = res.progress + "%"
}else{
this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
this.dltDownLvWc = res.progress + "%"
}
});
}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){
}
});
//#endif
//#ifdef MP-WEIXIN
//小程序对文件下载并不友好,不建议使用小程序当做下载器
const FileSystemManager = wx.getFileSystemManager();
FileSystemManager.saveFile({//下载成功后保存到本地
tempFilePath:data.tempFilePath,
filePath:wx.env.USER_DATA_PATH + "/" + sFileName,
success(res2){
if(res2.errMsg == 'saveFile:ok'){
// 判断手机平台是 Android 还是 IOS
if (uni.getSystemInfoSync().platform === 'android') {
// console.log('运行Android上')
uni.showModal({
title:"保存地址为",
content:"手机存储/Android/data/com.tencent.mm/MicroMsg/wxanewfiles"
})
} else {
// console.log('运行iOS上')
uni.showToast({
title:"请转移APP下载",
icon:"none"
})
}
}else{
uni.showToast({
title:"下载失败",
icon:"none"
})
}
},
fail(){
uni.showToast({
title:"下载失败",
icon:"none"
})
}
})
//#endif
}else{
this.loadProgress = 0;
uni.showToast({
icon:"none",
mask:true,
title:"下载失败"
})
}
},
fail:(err) => {
this.arcZzShow = false;
this.loadProgress = 0;
uni.showToast({
icon:"none",
mask:true,
title:"下载失败"
})
}
})
downloadTaskt.onProgressUpdate((res) => {
this.loadProgress = res.progress;
if (this.loadProgress < 100) {
} else {
this.loadProgress = 0;
}
if(res.totalBytesExpectedToWrite < 10485760){
this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1024) + "KB";
this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1024) + "KB";
this.dltDownLvWc = res.progress + "%"
}else{
this.dltDownLvNew = Math.ceil(res.totalBytesWritten / 1048576) + "M"
this.dltDownLvAll = Math.ceil(res.totalBytesExpectedToWrite / 1048576) + "M";
this.dltDownLvWc = res.progress + "%"
}
});
}
},//点击下载END
// 给下载的文件重命名
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();
}
}
}
</script>
五、有可能是坑
1、有时候手机和平板必须有wps才可以打开
2、打开文件可能存在跨域,这个需要后台去进行配置cors
3、使用uni.downloadFile()的文件路径(url)必须是浏览器能直接访问的文件。比如:http://xx/images/abc.pdf这种格式。 否则调用 uni.openDocument 是失败的,原因可能是无法识别文件类型
4、
版权声明:本文标题:【uniapp】微信小程序中的视频下载和分享、PDF下载和分享、完整下载(图片、视频、各种文件) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1729659574a1209544.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论