2015-11-02 35 views
3

我使用Koa作爲Web服務器來爲我的聚合物應用程序提供服務。在前臺按下按鈕localhost:3000/export被調用。我想在將一些文件打包成zip壓縮文件後將文件下載文件下載到客戶端。用Koa啓動文件下載

如何在Koa.js中做到這一點?

下面是關於如何做到這一點在快車(另一種選擇將是download-helper

app.get('/export', function(req, res){ 

    var path = require('path'); 
    var mime = require('mime'); 

    var file = __dirname + '/upload-folder/dramaticpenguin.MOV'; 

    var filename = path.basename(file); 
    var mimetype = mime.lookup(file); 

    res.setHeader('Content-disposition', 'attachment; filename=' + filename); 
    res.setHeader('Content-type', mimetype); 

    var filestream = fs.createReadStream(file); 
    filestream.pipe(res); 
}); 

我正在尋找的是這樣的一個例子:

router.post('/export', function*(){ 
    yield download(this, __dirname + '/test.zip') 
}) 

回答

15

你應該能夠簡單地將this.body設置爲文件流

this.body = fs.createReadStream(__dirname + '/test.zip'); 

然後根據需要設置響應頭。

this.set('Content-disposition', 'attachment; filename=' + filename); 
this.set('Content-type', mimetype); 
6

對於別人誰在將來看到這個,這是值得一提的還有在response對象,您可以使用設置Content-Dispositionattachment一個指定的文件名上attachment方法的建立。所以,你可以這樣做:

this.attachment('hello.txt') 

那將是同樣的事情如下:

this.set('Content-disposition', 'attachment; filename=hello.txt') 
1

瀏覽器的默認行爲是顯示文件,不要下載。要執行下載,您需要執行此操作:

this.header("Content-Type", "application/force-download") 
this.header('Content-disposition', 'attachment; filename=' + filename);