<a>实现文件下载的限制
文章目录
今天,同事问了我一个问题,她使用a标签的donload属性的写法去实现图片下载,而在chrome浏览器点击链接却是新开标签页而不是下载链接。
想通过<a download='...'></a>下载图片资源,必须满足一下其中一个条件:
- 图片文件与页面不能跨域;
或者 - 页面与图片文件跨域,但服务器强制保存文件(响应头设置
Content-Disposition为attachment)
本地模拟文件强制下载
npm install -g superstatic在test.png目录下新建文件superstatic.json
{
"headers": [
{
"source": "**/*.@(jpg|jpeg|gif|png)",
"headers": [
{
"key": "Content-Disposition",
"value": "attachment"
}
]
}
]
}然后启动本地服务器
superstatic . --port 8080 --host 127.0.0.1
// 即可访问图片地址:http://127.0.0.1:8080/test.png
新建html文件,用VS CODE插件Live Serve打开页面。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="http://127.0.0.1:8080/test.png" download="test.png">下载</a>
</body>
</html>点击链接直接下载图片, 测试通过。
参考文章
- Content-Disposition~强制浏览器保存文件
- Force to download image instead of opening url link to image
- superstatic
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论