export const downloadFile = (filename, fileUrl) => {
const token = getToken();//獲取當前登錄的token方法
const xhr = new XMLHttpRequest()
const url = fileUrl;//請求的api
xhr.open('get', url, true)
xhr.setRequestHeader('Authorization', `${token}`) // 給後端發送請求頭
xhr.responseType = 'blob'
xhr.onload = function(e) {
if (this.status === 200) {
const blob = this.response
const urlObject = window.URL || window.webkitURL || window
const export_blob = new Blob([blob])
const a = document.createElement('a') // 利用a標籤特性下載
const url = urlObject.createObjectURL(export_blob)
a.href = url
a.download = filename
a.click()
}
}
xhr.send()
}
這個使用是在Glory-Fast
項目的用戶的列表下載模塊,用戶導出整個用戶列表的excel,有興趣可以看一下項目地址,具體使用位置如下圖的用戶導出button
現階段做過的項目涉及下載的有兩種
export const downloadFile = function (fileurl,downloadToken) {
var url = appServerUrl;
const headers = {
'Content-Type': 'text/plain; charset=UTF-8',
"Token": downloadToken,
"Host": host,
"Connection": 'keep-alive',
"User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',
"Accept": '*/*',
"Referer": appHost,
"Origin": appHost,
"Sec-Fetch-Mode": 'no-cors'
};
return OSS.urllib.request(url, {
method: 'GET',
headers
}).then(function (result) {
var creds = JSON.parse(result.data);
var client = new OSS({
region: region,
accessKeyId: creds.AccessKeyId,
accessKeySecret: creds.AccessKeySecret,
stsToken: creds.SecurityToken,
bucket: bucket
});
var result = client.signatureUrl(fileurl, {
response: {
'content-disposition': 'attachment; filename="' + getFilenambypunct(fileurl,'_') + '"'
}
});
window.location = result;
return result;
});
};