2016-03-08 74 views
0

存在一個可動態創建文件(zip)以供下載的url。 http://example.com/generateZipFile.phpNode.js:從PHP網址下載(自動生成的)文件

在瀏覽器中,打開url只是打開下載對話框,用戶可以將文件保存到他們的硬盤。

我需要了解如何使用Node.js

我曾嘗試下面的代碼會自動下載此文件:

var file = fs.createWriteStream("http://example.com/generateZip.php"); 
var request = http.get(URL, function(response) { 
    response.pipe(file); 
}); 

但是它僅下載的似乎是一個HTML重定向頁面的內容zip文件的當前咒語,而不是壓縮文件本身:

> <head><title>Document Moved</title></head> <body><h1>Object 
> Moved</h1>This document may be found <a 
> HREF="http://example.com/generated12345.zip">here</a></body> 

我不能硬編碼的zip文件的生成的名稱,因爲它可能會改變。

+0

看看[快車下載](http://stackoverflow.com/a/7288883/3828573) – Shayan

+0

如果您需要手動刮cheerio可以幫助你,但節點 - metainspector會爲您提供遠程網頁的鏈接。 – MrVaykadji

回答

1

http模塊不支持重定向查詢。您可以使用request模塊:

require('request') 
    .get('http://example.com/generateZip.php') 
    .on('error', function(error) { 
    console.log(error) 
    }) 
    .pipe(require('fs').createWriteStream(__dirname + '/tmp.file'))