我寫了一個演示應用程序與此玩了一下:
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