微信浏览器无法下载文件,我们可以跳转外部浏览器进行下载。
首先绑定按钮事件(我这里用的uniapp开发)
<button class="btn" @click="downFile">点击下载
然后判断当前页面是否是微信浏览器,若是,提示用户打开右上角选择浏览器打开链接,若不是,进行下载
isWxBrowser = () => {
// 判断是否H5微信环境,true为微信浏览器
const ua = navigator.userAgent.toLowerCase()
return ua.match(/MicroMessenger/i) == 'micromessenger' ? true : false
}
进入默认浏览器后对文件进行下载(这里返回的是文件流)
resolveBlob = (res, fileName) => {
const aLink = document.createElement('a')
var blob = new Blob([res])
var fileName = fileName
fileName = fileName.replace(/\"/g, '')
aLink.style.display = 'none'
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.removeChild(aLink);
}
完整的代码
<template>
<view>
<div style="margin:20px">
<button class="btn" @click="downFile">点击下载</button>
</div>
</view>
</template>
import {
isWxBrowser,
resolveBlob
} from './upload.js'
export default {
name: 'downLoadFile',
data() {
return {
isWx: isWxBrowser(), // 是否微信内部浏览器
filePath: '',
fileName: ''
};
},
onLoad(options) {
},
methods: {
wxBrowserModal() {
if (this.isWx) {
uni.showModal({
title: '提示',
content: '请点击右上角,在浏览器打开页面下载。',
showCancel: false
})
}
return !this.isWx // 方便downFile方法使用,return false停止执行下载
},
downFile() {
this.wxBrowserModal() && this.downLoadFile()
},
downLoadFile() {
api.downloadFile().then(res => {
resolveBlob(res, this.fileName)
})
},
},
}
upload.js文件
export const isWxBrowser = () => {
// 判断是否H5微信环境,true为微信浏览器
const ua = navigator.userAgent.toLowerCase()
return ua.match(/MicroMessenger/i) == 'micromessenger' ? true : false
}
export const resolveBlob = (res, fileName) => {
const aLink = document.createElement('a')
var blob = new Blob([res])
var fileName = fileName
fileName = fileName.replace(/\"/g, '')
aLink.style.display = 'none'
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.removeChild(aLink);
}