前端開發中vue+axios實現文件下載,附源碼

前端開發中vue+axios實現文件下載,附源碼

組件內部的js

前端開發中vue+axios實現文件下載,附源碼

前端開發中vue+axios實現文件下載,附源碼

前端開發中vue+axios實現文件下載,附源碼

工具類js

前端開發中vue+axios實現文件下載,附源碼

實現效果:

前端開發中vue+axios實現文件下載,附源碼

主要js源碼:

methods: {

async downloadPre(){

let res = await Service.downloaded(api.img);

console.log(res.data);

let type = res.data && res.data.type || 'image/jpeg';

if (!res) {

return

}

let url = window.URL.createObjectURL(new Blob([res.data],{type:type}));

let link = document.createElement('a')

link.style.display = 'none'

link.href = url

link.setAttribute('download', 'excel.jpeg')

document.body.appendChild(link)

link.click()

document.body.removeChild(link) // 下載完成移除元素

window.URL.revokeObjectURL(url) // 釋放掉blob對象

},

}

工具類js主要代碼:

export function download(url,data = {}){//文件下載

return new Promise((resolve, reject) => {

axios({

method: "get",

url: url,

data: data,

responseType: "blob"

// responseType: "arraybuffer",

})

.then(response => {

resolve(response)

}).catch(function(err){

reject(err)

})

})

}

前端開發中vue+axios實現文件下載,附源碼

功能實現完成,簡單粗暴。


分享到:


相關文章: