2016-03-08 47 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'))