前端下載文件的方式及跨域下載


node服務

const dir = path.join(__dirname, 'download')

app.get('/downloadfile', (req, res) => {
	const { filename } = req.query
	var filepath = path.join(dir, filename) // 需要下載的文件路徑
	var fileStream = fs.createReadStream(filepath)
	res.setHeader('Content-type', 'application/octet-stream')
	res.setHeader('Content-Disposition', `attachment;filename=${filename}`) // 需要下載的文件名
	fileStream.on('data', function (data) {
		res.write(data, 'binary')
	})
	fileStream.on('end', function () {
		res.send()
	})
})

二進制下載

this.$axios({
     method: "get", //請求方式
     responseType: "blob", //告訴服務器我們需要的響應格式
     url: "file/download", //地址
   }).then(res => {
     let url = window.URL.createObjectURL(new Blob([res.data])); //轉換為可用URl地址
     let link = document.createElement("a"); //創建a標簽
     link.style.display = "none"; //使之不可見
     link.href = url; //賦URL地址
     link.setAttribute("download", item.fileName); //設置下載屬性、以及文件名
     document.body.appendChild(link); //將a標簽插至頁面中
     link.click(); //強制觸發a標簽事件
}

URL 下載

后端返回URL下載路徑,前端直接放置在a標簽的href屬性,並賦予a標簽download屬性。

Download() {
    let link = document.createElement("a"); //創建a標簽
    link.style.display = "none"; //使其隱藏
    link.href = this.Data.filePath; //賦予文件下載地址
    link.setAttribute("download", this.Data.fileName); //設置下載屬性 以及文件名
    document.body.appendChild(link); //a標簽插至頁面中
    link.click(); //強制觸發a標簽事件

}

跨域下載

URL下載方式中,遇到mp4/jpg/png等瀏覽可以識別的文件格式時,直接在瀏覽器中打開了該文件。

download屬性也受同源策略的影響,即非同一端口下不能直接下載第三方文件。

img

document.querySelector('button').onclick = function () {
	const xhr = new XMLHttpRequest()
	xhr.open('GET', 'http://127.0.0.1:9003/1.jpg', true)
	xhr.responseType = 'blob'
	xhr.onload = () => {
		if (xhr.status === 200) {
			const fileType = xhr.response.type // 文件類型,可以根據此類型設置對應的文件名后綴.
			const suffix = fileType === 'image/jpeg' ? '.jpg' : '.txt' // 設置文件后綴名
			var aEle = document.createElement('a') // 創建a標簽
			// 字符內容轉變成blob地址
			blob = new Blob([xhr.response])
			aEle.style.display = 'none'
			document.body.append(aEle)
			var urlObject = window.URL.createObjectURL(blob)
			aEle.href = urlObject
			aEle.download = 'fileName' + suffix // 下載的文件名
			aEle.click()
			document.body.removeChild(aEle)
		}
	}
	xhr.send()
}

如果返回的是下載類容

const aEle = document.createElement('a') // 創建a標簽
blob = new Blob([res.data])
aEle.download = fileName // 設置下載文件的文件名
aEle.href = URL.createObjectURL(blob)
aEle.click() // 設置點擊事件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM