/**
* 获取响应头content-disposition中的文件名
* (例: content-disposition: "attachment;filename=xxx.doc")
* @param contentDisposition
* @returns
*/
export const getFileName = (contentDisposition: string) => {
try {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i;
const matches = filenameRegex.exec(contentDisposition);
const fileName = matches && decodeURI(matches[1]);
return fileName;
} catch (error) {
console.error(error);
}
}
/**
* 文件下载
* @param ab
* @param fileName
*/
export const downloadFile = (ab: ArrayBuffer, fileName: string) => {
try {
const blob = new Blob([ab]);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
}
}
前端通过a标签实现文件下载
最新推荐文章于 2024-06-28 10:00:12 发布