from: atangshare/content-disposition

MDN Content-Disposition

The HTTP Content-Disposition header indicates whether content should be displayed inline in the browser as a web page or part of a web page or downloaded as an attachment locally.

The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a ‘Save as’ dialog, prefilled with the value of the filename parameters if present).

public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="/preview">预览</a>
<a href="/download">下载</a>
</body>
</html>

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import http from 'http';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const server = http.createServer(async (req, res) => {
if (req.url === '/') {
const data = await fs.readFile(path.join(__dirname, 'public', 'index.html'));
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(data);
} else if (req.url === '/preview') {
const data = await fs.readFile(path.join(__dirname, 'public', 'sample.pdf'));
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline'
});
res.end(data);
} else if (req.url === '/download') {
const data = await fs.readFile(path.join(__dirname, 'public', 'sample.pdf'));
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment;filename="sample2.pdf"'
});
res.end(data);
}
});

server.listen(3000, () => {
console.log('Server is running on 3000');
});

result

$ node server.js
Server is running on 3000

Click Download link will download the file to local, and the file name will use the file name specified in Content-Disposition.

Click Preview Link will preview the file directly in the browser.

Edited on