存在一个动态创建文件 (zip) 供下载的 url。 http://example.com/generateZipFile.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 文件的当前语法,而不是 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 文件的生成名称进行硬编码,因为它可能会发生更改。
最佳答案
http
模块不支持查询重定向。您可以使用request
模块:
require('request')
.get('http://example.com/generateZip.php')
.on('error', function(error) {
console.log(error)
})
.pipe(require('fs').createWriteStream(__dirname + '/tmp.file'))
关于javascript - Node.js:从 PHP URL 下载(自动生成的)文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35860965/