天天看点

VUE实现文件下载

第一:请求的responseType为blob,以post请求为例:

downloadClick(row){
        let entity = {
          id: row.id,
          filename: row.filename,
        }
        this.$http.post('/v1/FileManage/downloadFile', entity ,{responseType: 'blob'}).then((response)=> {
         this.download(response.body,row)
        });
      },
           

第二步:请求成功,拿到response里面的数据后,调用download函数(创建a标签,设置download属性,插入到文档中并click)

methods: {
    // 下载文件
    download (data,row) {
        if (!data) {
            return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        // 获取文件名
        // download 属性定义了下载链接的地址而不是跳转路径
        link.setAttribute('download', row.filename)
        document.body.appendChild(link)
        link.click()
    }
}
           

传送门:后台代码:https://blog.csdn.net/mibi8840/article/details/86742134