Content-Disposition
Content-Disposition 息头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。
Content-Disposition只会影响部分href、和地址栏直接输入结果等,直接在img.src中使用并不会下载文件。
举个简单的例子。先准备两个图片wm.png、wm2.png, 并设置下载与内联
1
2
3
4
5
6
7
8// nodejs code
setHeaders: function(res, path, stats) {
if (path.includes("static/image/wm.png")) {
res.setHeader("Content-Disposition", "attachment;filename='hanmeimei.png'");
} else if (path.includes("static/image/wm2.png")) {
res.setHeader("Content-Disposition", "inline");
}
}
写一段简单的html代码去加载它们。
1
2
3
4
5
6
7
8// html code
<a href="static/image/wm.png" target="_blank">下载图片1</a>
<a href="static/image/wm2.png" target="_blank">
打开一个新的窗口,窗口里显示图片2</a>
<h1>图片1</h1>
<img src="static/image/wm.png" alt="" />
<h2>图片2</h2>
<img src="static/image/wm2.png" alt="" />
再测试一下脚 本。
1
2
3
4
5
6
7
8
9
10
11<script>
// img ,会直接显示图片
let c = new Image();
c.src = "static/image/wm.png";
document.body.appendChild(c);
// 下载文件wm.png
window.location.href = "static/image/wm.png";
// 不会下载, 会内联显示
window.location.href = "static/image/wm2.png";
</script>