问题
最近开发中遇到的问题,文件名中含有点和逗号字符,当使用a标签的download属性下载内容时,如果不指定后缀,部分浏览器无法自动识别文件后缀。如下图所示:



定义用法
download 属性定义了下载链接的地址。
href 属性必须在 标签中指定。
属性同样可以指定下载文件的名称。
文件名称没有限定值,浏览器会自动在文件名称末尾添加该下载文件的后缀 (.img, .pdf, .txt, .html, 等),添加后缀将使用指定后缀,不会重复出现。
案例:
-
- function downloadData(){
- // 使用a的download属性下载文件
- let filename = '文件名称';
- let data = '数据';
- let blob = new Blob([data],{type:'application/vnd.ms-excel'})
- let a = document.createElement('a');//创建a元素
- a.href = URL.createObjectURL(blob);
- a.download = filename;
- a.click();//触发a的点击事件
- //URL.revokeObjectUrl(a.href)
- a = null;
- }
解决方案
注意当使用download属性实现下载时要添加后缀!!!
- downloadRenewal(data) {
- const id = data.renewal_id;
- this.http.post(this.commonApiService.apiList.apis.license_in.renewalCertificateDownload, { id }).subscribe((res) => {
- if (res.code !== 0) {
- this.msg.error(res.msg)
- return
- } else {
- fetch(res.row.download_url)
- .then(res => res.blob().then(blob => {
- const a = document.createElement('a'),
- url = window.URL.createObjectURL(blob),
- // 强行指定文件后缀
- filename = `${data.renewal_order_name}-${data.order_no}.pdf`;
- a.href = url;
- a.download = filename;
- console.log(a)
- a.click();
- window.URL.revokeObjectURL(url);
- }));
- }
- })
- }
兼容性(浏览器支持)

问题完美解决,YYDS! 欢迎在评论区交流。
如果文章对你有所帮助,❤️关注+点赞❤️鼓励一下!博主会持续更新。。。。
