先封装一个基础类库
import $common from '@/common/common.js';
export default {
saveFile: function(url, success) {
const dA = document.createElement("a");
dA.download = ''; // 设置下载的文件名,默认是'下载'
dA.href = url;
document.body.appendChild(dA);
dA.click();
dA.remove(); // 下载之后把创建的元素删除
success(); //运行回调
},
//点击事件触发此函数保存文件
download(url) {
$common.loading();
uni.downloadFile({
url: url,
success: (res) => {
const fileUrl = res.tempFilePath;
// #ifdef H5
this.saveFile(fileUrl, () => {
setTimeout(() => {
$common.loading(false);
$common.tips('下载成功');
}, 1500)
});
// #endif
// #ifndef H5
uni.saveImageToPhotosAlbum({
filePath: fileUrl,
success: () => {
uni.showToast({
title: "下载成功"
});
},
complete: () => {
$common.loading(false);
}
});
// #endif
}
})
},
//长按图片触发此函数,保存图片
operator(url) {
$common.loading();
uni.showActionSheet({
itemList: ["保存图片"],
success: (res) => {
if (res.tapIndex === 0) { //数组下标
uni.showLoading({
mask: true,
title: "下载中..."
});
uni.downloadFile({
url: url,
success: (res) => {
const fileUrl = res.tempFilePath;
// #ifdef H5
this.saveFile(fileUrl, () => {
$common.loading(false);
});
// #endif
// #ifndef H5
uni.saveImageToPhotosAlbum({
filePath: fileUrl,
success: () => {
uni.showToast({
title: "下载成功"
});
},
complete: () => {
$common.loading(false);
}
});
// #endif
}
})
}
}
})
}
}
然后在页面调用
//下载视频
import $download from '@/common/download.js';
/*其他代码*/
downloadVideo() {
$download.download(this.videoUrl);
}