1. 业务场景:可以打开用户的文件夹
实现思路:网页js没有权限打开资源管理器
ActiveXObject;js没有权限打开资源管理器,桌面应用才可以。 移动端和pc端都得通过打包成原生应用才行。
pc端用electron打包桌面应用,或者移动端依赖原生app,或者weex reactnative、uniapp等
纯web不行的,想象一下,浏览器打开百度页面,然后百度就直接访问本地微信qq的聊天记录 图片肯定不可能的
实现方式
a:ActiveXObject;只针对ie实现不了
b:桌面应用 electorn +vue
c:小程序依赖微信框架,移动端用weex reactnative、uniapp
2.业务场景:读取上传txt 的内容
实现方式:
<el-upload action="/"
ref="upload"
accept=".txt"
:before-upload="beforeUpload"
:disabled="this.fileList.length !== 0"
:default-file-list="this.fileList"
>
<el-button type="primary" :disabled="this.fileList.length !== 0">上传文件</el-button>
</el-upload>
beforeCreate() {
// 读取文件
FileReader.prototype.reading = function ({encode} = pms) {
let bytes = new Uint8Array(this.result); //无符号整型数组
let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
return text;
};
/* 重写readAsBinaryString函数 */
FileReader.prototype.readAsBinaryString = function (f) {
if (!this.onload) //如果this未重写onload函数,则创建一个公共处理方式
this.onload = e => { //在this.onload函数中,完成公共处理
let rs = this.reading();
console.log(rs);
};
this.readAsArrayBuffer(f); //内部会回调this.onload方法
};
},
methods:{
beforeUpload(file){
this.fileList = [file]
console.log('选择了文件beforeUpload')
// 读取数据
this.read(file);
return false
},
read(f) {
let rd = new FileReader();
rd.onload = e => {
//this.readAsArrayBuffer函数内,会回调this.onload函数。在这里处理结果
let cont = rd.reading({encode: 'GBK'});
console.log(cont);
let formerData = this.textData;
this.textData = formerData + "\n" + cont;
};
rd.readAsBinaryString(f);
}
}
3. 业务场景 后台给一个链接实现a标签下载
实现方式:
a:利用widow方式:whidow,open/href 参数为url链接
b:a标签download 属性;动态建立一个标签
关键代码:
const url = window.URL.createObjectURL(res.data)
const a = document.createElement('a')
a.href = url
a.download = getFileNameFromUrl(item)
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
c:与后台结合的情况:
export function $a({ symbol, address, params }) {
return request({
url: `/download`,
method: 'get',
params,
responseType: 'blob', //blob格式
})
}
$a(params).then((res) => {
const content = res.data
const blob = new Blob([content])
let fileName = `${_this.$t('chainMonitor.transactionBehavior.TxsRecord')}${new Date().getTime()}.xlsx`
const contentDisposition = res.headers['content-disposition']
if (contentDisposition) {
fileName = window.decodeURI(
res.headers['content-disposition'].split('=')[1],
'UTF-8'
)
}
if ('download' in document.createElement('a')) {
// 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
备注:pdf 图片如果是不在同一域名下的会重新打开一个界面下载,doc xlsx不会,开发环境会这样,放测试环境就好了