端下载文件如何取文件名

321 阅读1分钟

前端下载文件如何取文件名

1.通常乱码有两种形式

1.编码后的 URI 组件字符串,通常带有%

image.png

其中filename=%E6%B2%9B%E5%8E%BF%E4%BB%93%E5%BA%93%E7%9B%98%E7%82%B9%E7%BB%93%E6%9E%9C.xlsx

这是后端使用类似于encodeURIComponent的函数帮忙做了处理,前端可以直接通过decodeURIComponent获取文件名。 如果是django可以通过escape_uri_path 函数做处理

const encodeFileName = encodeURIComponent('我是文件名.xlsx')
console.log(encodeFileName) //%E6%88%91%E6%98%AF%E6%96%87%E4%BB%B6%E5%90%8D.xlsx
const decodeFilename = decodeURIComponent(encodeFileName)
console.log(decodeFilename) //我是文件名.xlsx

2. 没有%的字符串,这一般是后端未处理的文件名

image.png ?utf-8?b?表示用base64编码的字符串,使用 utf-8 字符集。

需要使用atob将 Base64 编码的字符串解码成一个二进制字符串,最后再转成正常字符串


const str = "?utf-8?b?YXR0YWNobWVudDsgZmlsZW5hbWU95oiR5piv5paH5Lu25ZCNLnhsc3g"
const base64Str = str.split('?utf-8?b?')[1]

// Base64 解码
const binaryString = atob(base64Str)
// 创建一个 Uint8Array 来存储解码后的二进制数据
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
  bytes[i] = binaryString.charCodeAt(i)
}

// 使用 TextDecoder 将 Uint8Array 转换为 UTF-8 字符串
const decoder = new TextDecoder("utf-8")
const filename = decoder.decode(bytes)
console.log(filename) // attachment; filename=我是文件名.xlsx

2.常见的获取文件名失败的两种情况

1.如果res.headers中没有content-disposition,需要找后端放开,暴露这个字段

2.如果打印不出res.headers,说明前端代码使用axios拦截器拦截Response的时候return response.data,而不是return response