res.attachment()
向網頁瀏覽器或其他使用者代理程式表明,此回應中傳送的輸出檔案下載應「另存為...」而非「開啟」,並可選擇性地指定新下載檔案在磁碟上的名稱。
具體來說,這會將目前回應的 "Content-Disposition" 標頭設定為 "attachment"。如果提供了 filename
,則 "Content-Type" 將根據檔案的副檔名(例如 .jpg
或 .html
)自動設定,而 "Content-Disposition" 標頭將設定為 "filename=filename
"。
res.attachment([filename]);
此方法應在串流傳輸檔案位元組之前呼叫。
例如,如果您將 uploads hook 與 actions2 搭配使用
fn: async function({id}, exits) {
var file = await LegalDoc.findOne({ id });
if(!file) { throw 'notFound'; }
this.res.attachment(file.downloadName);
var downloading = await sails.startDownload(file.uploadFd);
return exits.success(downloading);
}
就是這樣!當在瀏覽器中存取時,此動作下載的檔案將另存為新檔案(例如「Tax Return (Lerangis, 2019)」),而不是直接在瀏覽器本身中開啟。
在底層,res.attachment()
沒有做任何花俏的事情,它只是設定回應標頭
res.attachment();
// -> response header will contain:
// Content-Disposition: attachment
res.attachment('Tax Return (Lerangis, 2019).pdf');
// -> response header will contain:
// Content-Disposition: attachment; filename="Tax Return (Lerangis, 2019).pdf"
// Content-Type: application/pdf