HTTP协议 之 Content-Disposition

完整示例代码参考Content-Disposition

Contents

Startup

1
2
3
mkdir node-download && cd node-download

npm init && cnpm i --save express
1
vim app.js
1
2
3
4
5
6
7
8
9
10
var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
console.log('服务启动');
});
1
2
3
node app.js

curl localhost:3000

Node

1
vim app.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
var fs = require('fs');
var express = require('express');
var app = express();

app.get('/preview', function (req, res) {
var filename = 'image.jpg';
res.sendFile(filename, {
root: __dirname
});
});

app.get('/download', function (req, res) {
var filename = 'image.jpg';
res.download(filename);
});

app.get('/deleteAfterDownload', function (req, res) {
var filename = 'temp.jpg';
fs.writeFileSync(filename, fs.readFileSync('image.jpg'));
var stream = fs.createReadStream(filename);
stream.once("end", function () {
stream.destroy();
fs.unlinkSync(filename);
}).pipe(res);
});

app.listen(3000, function () {
console.log('服务启动');
});
1
node app.js

HTTP

1
2
curl -I localhost:3000/download
# Content-Disposition: attachment; filename="image.jpg"
1
vim app.js
1
2
3
4
5
6
7
8
9
10
app.get('/deleteAfterDownload', function (req, res) {
var filename = 'temp.jpg';
fs.writeFileSync(filename, fs.readFileSync('image.jpg'));
var stream = fs.createReadStream(filename);
res.set('Content-Disposition', 'attachment; filename="temp.jpg"');
stream.once("end", function () {
stream.destroy();
fs.unlinkSync(filename);
}).pipe(res);
});
1
ndoe app.js

HTTP协议Content-Disposition响应头: inline(默认值)表示在网页中显示 attachment表示下载至本地