关于http的Content-Disposition头的作用

在浏览器中,请求文件有两种行为,一种是在浏览器中直接打开,一种是下载到本地。这种行为是由HTTP的Content-Disposition header来决定的。
在HTTP的响应报文头部中,Content-Disposition的值可以为下列几种:

1
2
3
Content-Disposition: inline
Content-Disposition: attachment
Content-Disposition: attachment; filename="filename.jpg"

在HTTP场景中,第一个参数或者是inline(默认值,表示回复中的消息体会以页面的一部分或者整个页面的形式展示),或者是attachment(意味着消息体应该被下载到本地;大多数浏览器会呈现一个“保存为”的对话框,将filename的值预填为下载后的文件名,假如它存在的话)。

此外content-type为multipart/form-data的post请求中也会使用到Content-Disposition头部,对应form-data中不同的字段。

nodejs demo
1
2
3
4
5
6
7
8
9
10
11
12
13
const http = require("http");
const fs = require("fs");

http.createServer(function (req, res) {
let readStream = fs.createReadStream("./index.html");

res.writeHead(200, {
"Content-Disposition": "attachment",
// "Content-Disposition": "inline",
});

readStream.pipe(res);
}).listen(8000);