JS download file method with token and no page jump-Kaiqisan

JS way to download files

ヤッハロー, Kaiqisan すうう, 一つふつうの学生プログラマである, when working on the project, some private file downloads need to upload the user token in advance, so this makes it impossible to directly use the a tag to add the address and directly get the data from the backend. So, today I plan to put aside the encapsulated method and start from scratch.

It is used when downloading needs to use token to verify identity.

Now take axios as an example to illustrate the way

/* a.js */
import axios from 'axios'	// 其他导包方法详见官网

axios({
    
    
   	methods: 'get',	// 一般获取文件使用get方法
    url: urlName,	// 自己写路径
    headers: {
    
    
        'token': 'xxxxxxxxxxxxxxx'  // header处添加token等凭证
    },
    responseType: 'blob'  	// 这句话是关键,意思是希望后端返回Blob类型属性
    //(Blob对象表示一个不可变、原始数据的类文件对象。) 
    // File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
}).then({
    
    
    const blob = new Blob([res.data], {
    
    	
        // 创建一个新的Blob对象来接收后端的文件,这里第一个参数必须是数组类型,否则下载必出错。
        type: 'application/octet-stream' 
        // type,表明该 Blob 对象所包含数据的 MIME 类型,这需要前后端统一规划
    })
    let link = document.createElement('a')	
    let body = document.querySelector('body')
    link.href = window.URL.createObjectURL(blob) // 创建一个下载文件的URL,它指向blob,因为Blob对象在之前在接收后端发来的文件流信息。因为是Blob对象,所以不会跳转页面
		

    // 以后还有新增的东西的话再加
    link.download = 'xxxxxx' // 自己制定下载文件的文件名
    // 兼容火狐浏览器
    link.style.display = 'none'	// 让这个a标签不可见
    body.appendChild(link)
    link.click()		// 创建了新的a标签之后模拟点击事件,开始传输文件
    body.removeChild(link)	// 下载完成之后,移除按钮,垃圾回收,减少页面内存消耗
    window.URL.revokeObjectURL(link.href)	// 移除之前使用createObjectURL创建的URL,垃圾回收
})

Key statement:

responseType: 'blob'

const blob = new Blob(data, params)

window.URL.createObjectURL(url)

appendChild(obj)

removeChild(obj)

window.URL.revokeObjectURL(obj)

to sum up

Universal code, it is recommended to remember that it can be used everywhere.

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108099206