简体   繁体   English

Node.js:从PHP URL下载(自动生成的)文件

[英]Node.js: Download an (auto-generated) file from a PHP URL

There exists a url which dynamically creates a file (zip) for download. 存在一个URL,该URL动态创建一个文件(zip)供下载。 http://example.com/generateZipFile.php http://example.com/generateZipFile.php

In a browser, opening the url simply opens the download dialog box, and a user can save the file to their hard drive. 在浏览器中,打开URL只会打开下载对话框,用户可以将文件保存到他们的硬盘中。

I need to automatically download this file using node.js 我需要使用node.js自动下载此文件

I have tried the following code: 我尝试了以下代码:

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

However it only downloads the content of what appears to be a HTML redirect page to the current incantation of the zip file, not the zip file itself: 但是,它只会将似乎是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>

I can not hard code the generated name of the zip file, as it is subject to change. 我无法对zip文件的生成名称进行硬编码,因为它可能会更改。

http module does not support redirection for queries. http模块不支持查询重定向。 You can use request module: 您可以使用request模块:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM