说明
最近有些空余时间开始着手优化我那个吉他自学小助手的微信小程序,其中有一个功能是下载吉他谱到本地,开始以为只是很简单的拿到图片url然后down下来就好了,其实不然...最终通过google解决了这个问题,现在记录一下,以便后续翻阅。
少废话先看东西
流程梳理
获取图片远程地址数组-->遍历拿到图片缓存(临时地址)(wx.getImageInfo)-->保存缓存图片到本地(wx.saveImageToPhotosAlbum)
完整代码
子组件代码逻辑
//子组件download-file.vue
<template>
<div></div>
</template>
<script>
export default {
props: {
urls: {
default: ""//通过父组件传递远程图片路径数组
}
},
watch: {
urls() {
if (this.urls.length > 0) {
this.downLoadImage(this.urls);//监听变化
}
}
},
methods: {
//拿到图片的临时路径
getImageInfo(url) {
var cache = {};
return new Promise((resolve, reject) => {
/* 获得要在画布上绘制的图片 */
if (cache[url]) {
resolve(cache[url]);
} else {
const objExp = new RegExp(
/^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
);
if (objExp.test(url)) {
wx.getImageInfo({
src: url,
complete: res => {
if (res.errMsg === "getImageInfo:ok") {
cache[url] = res.path;
resolve(res.path);
} else {
reject(new Error("getImageInfo fail"));
}
}
});
} else {
this.cache[url] = url;
resolve(url);
}
}
});
},
downLoadImage(urls) {
const vm = this;
let temp = [];
if (urls.length > 0) {
urls.map((item, index) => {
vm.getImageInfo(item).then(res => {
temp.push(res);
vm.saveImageToLocal(res);
});
});
}
},
saveImageToLocal(path) {
//保存临时图片到本地
wx.saveImageToPhotosAlbum({
filePath: path,
success(res) {
console.log("success");
},
fail: function(res) {
console.log(res);
}
});
}
}
};
</script>
<style>
</style>
在父组件中引用
//news/detail.vue
//省略代码...
<button @click="download">下载</button>
//省略代码...
<download-file :urls="downLoadUrls" ref="myDownload"></download-file>
//省略代码...
async download() {
let vm = this;
const temp = [];
let data = await vm.$net.get(vm.$apis.articleDetails, {
id: vm.item.id
});
if (data.article.body.length > 0) {
data.article.body.map((item, index) => {
if (item.type == "img") {
temp.push(item.data);
}
});
}
vm.downLoadUrls = temp;
},