問題描述:項目中使用的是vue框架進行開發,因為文件下載存在權限問題,所以并不能通過 a 鏈接的 href 屬性直接賦值 URL進行下載,
(如果你的文件沒有下載權限,可以直接通過href屬性賦值URL的方法進行文件下載),所以使用vue-resource請求文件流后,借助Blob對象實現下載,
但是仍然存在解壓的問題(針對壓縮文件),而 docx等文檔格式主要出現的就是亂碼問題。
問題截圖:
出現以上解壓問題的代碼,通過vue-resource請求二進制文件
downloadFile(attachment) {let fileName = attachment.displayName;this.$http.get(strategyDownloadUrl + '/' + attachment.id).then((res) => {if(typeof(res.data) == 'string'){var blob = new Blob([res.data], {type:'application/octet-stream'})if (window.navigator.msSaveOrOpenBlob) {//msSaveOrOpenBlob方法返回bool值navigator.msSaveBlob(blob, fileName);//本地保存} else {var link = document.createElement('a');//a標簽下載link.href = window.URL.createObjectURL(blob);link.download = fileName;link.click();window.URL.revokeObjectURL(link.href);}}else{swal(res.data.msg,'','info')//個人彈窗忽視}})},
采用原生對象XHRHttpRequest進行文件請求(也可通過jquery的ajax進行文件請求),可以正常解壓文
downloadFile(attachment) {
let that = this
var ajax = new XMLHttpRequest()
ajax.responseType = 'blob'
ajax.open("GET",strategyDownloadUrl + '/' + attachment.id,true)
ajax.setRequestHeader('X-Authorization','Bearer ' + this.$store.state.token)
ajax.onreadystatechange = function(){
if(this.readyState == 4) {
if(this.status == 200) {
//console.log(this.response) // should be a blob
if(this.response.type == "application/octet-stream"){
that.downloadHandler(this.response,attachment.displayName)
}else{
swal('您要下載的資源已被刪除!','' , 'error')
}
} else if(this.responseText != "") {
//console.log(this.responseText);
}
} else if(this.readyState == 2) {
if(this.status == 200) {
this.responseType = "blob"
} else {
this.responseType = "text"
}
}
};
ajax.send(null);
},
downloadHandler(content, filename) {
var eleLink = document.createElement('a')
eleLink.download = filename
eleLink.style.display = 'none'
// 字符內容轉變成blob地址
var blob = new Blob([content],{type: "application/octet-stream"})
eleLink.href = URL.createObjectURL(blob)
// 觸發點擊
document.body.appendChild(eleLink)
eleLink.click()
// 然后移除
document.body.removeChild(eleLink)
},
如有不正確的地方,請指正交流,共同進步。