前言:
微信公众号不支持操作文件(保证微信用户数据安全性),可以下载预览一些图片,而已也要用微信公众号对于api
解决方法(属于偏方,如果项目同意可以用):
思路:
点击按钮,复制下载链接(利用document.execCommand("copy")方法),引导用户前往其它浏览器下载
注意:
document.execCommand("copy")方法在ios环境不可用,下面的方法可以解决这个问题
代码如下:
copyUrl(url) {
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
//ios系统
window.getSelection().removeAllRanges(); //这段代码必须放在前面否则无效
let inputDom = document.createElement("input");
// let copyDom = document.getElementById("copyDom"); //要复制文字的节点
// copyDom.appendChild(inputDom); // 把标签添加给body
document.body.appendChild(inputDom); // 把标签添加给body
inputDom.style.opacity = 0; //设置input标签设置为透明(不可见)
inputDom.value = url; // 修改文本框的内容
let range = document.createRange();
// 选中需要复制的节点
range.selectNode(inputDom);
// 执行选中元素
window.getSelection().addRange(range);
inputDom.select();
inputDom.setSelectionRange(0, inputDom.value.length); //适配高版本ios
// 执行 copy 操作
let successful = document.execCommand("copy");
let messageText = successful
? "请将此链接复制至手机或电脑浏览器打开并完成下载。"
: "链接复制失败!";
alert(messageText);
// 移除选中的元素
window.getSelection().removeAllRanges();
document.body.removeChild(inputDom);
} else {
//其他系统
let inputDom = document.createElement("input");
// let copyDom = document.getElementById('copyDom')
// copyDom.appendChild(inputDom);// 把标签添加给body
document.body.appendChild(inputDom);
inputDom.style.opacity = 0; //设置input标签设置为透明(不可见)
inputDom.value = url; // 修改文本框的内容
inputDom.select(); // 选中文本
// 执行选中元素
let successful = document.execCommand("copy"); // 执行浏览器复制命令
let messageText = successful
? "请将此链接复制至手机或电脑浏览器打开并完成下载。"
: "链接复制失败!";
alert(messageText);
document.body.removeChild(inputDom);
}
},