HTTP协议 之 Content-Disposition

完整示例代码参考Content-Disposition

Contents

  • Startup

  • Node

  • HTTP

Startup

mkdir node-download && cd node-download

npm init && cnpm i --save express
vim app.js
var express = require('express');
var app = express();

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

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

curl localhost:3000

Node

vim app.js
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('服务启动');
});
node app.js
  • 浏览器打开 http://localhost:3000/preview

  • 浏览器打开http://localhost:3000/download

  • 浏览器打开http://localhost:3000/deleteAfterPreview

HTTP

curl -I localhost:3000/download
# Content-Disposition: attachment; filename="image.jpg"
vim app.js
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);
});
ndoe app.js
  • 浏览器打开http://localhost:3000/deleteAfterDownload

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

你可能感兴趣的:(HTTP协议 之 Content-Disposition)