我試圖通過GET ajax調用來動態請求文件下載。我有以下的客戶端代碼:Node.js/Express:通過ajax下載文件
$(function() {
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "/download/" + "filename",
dataType: "json",
contentType: "application/json",
complete: function() {
console.log('Complete');
},
success: function() {
console.log('Success');
},
error: function() {
console.log('Error');
}
});
});
});
在節點服務器我也有以下行(請注意,我不知道這是否是這樣做的正確方法)
app.get('/download/:filename', function(req, res) {
console.log(req.params);
res.write(fs.readFileSync(__dirname + "/../public/javascripts/main.js", 'utf8'));
});
所以我想實際下載該JavaScript文件(最終動態地)。我會如何正確地做這件事?有些東西告訴我我需要指定標題/內容類型。
我很確定你不能用Ajax做到這一點。更好的策略是將文件加載到iframe *和*根據@Bit Destroyer的建議設置標題。 – apsillers
Per @apsillers建議,如果我沒有弄錯,當瀏覽器重定向到具有上述標題的文件時,它實際上並不從當前頁面瀏覽,而只是打開保存文件對話框。考慮到這一點,iframe可能是多餘的,但不要拿我的話來說。 (ba da dum) – jamesmillerio
@坐,有趣!我必須檢查一下,看看它是否可以跨瀏覽器使用。 – apsillers