我写了一个演示应用来玩这个:
app.js:
var express = require('express')
, http = require('http')
, path = require('path')
, fs = require('fs')
var app = express();
var data = JSON.parse(fs.readFileSync('hello.json'), 'utf8')
app.get('/hello.json', function(req, res) {
res.attachment('hello.json')
//following line is not necessary, just experimenting
res.setHeader('Content-Type', 'application/octet-stream')
res.end(JSON.stringify(data, null, 2), 'utf8')
})
http.createServer(app).listen(3000, function(){
console.log('Listening...')
});
hello.json:
{
"food": "pizza",
"cost": "$10"
}
仅使用 HTTP 标头,我相信这只是特定于浏览器的。从本质上讲,res.attachment 函数将Content-Disposition HTTP 服务器标头设置为attachment。某些浏览器(例如 Firefox)会提示您“另存为”。 Chrome 和 Safari 默认不支持。但是,您可以在 Chrome 或 Safari 的选项中更改此默认行为。我没有在 Internet Explorer 中进行测试。
我尝试更改 Content-Type 以查看是否会覆盖任何行为,但不会。
简而言之,您将无法覆盖用户的设置。
你可以在这里看到更多:How to force a Save As dialog when streaming a PDF attachment