You can use the http.request()
function to make a request to your externalURL
and then pipe()
the response back to res
. Using pipe()
will stream the file through your server to the browser, but it won't save it to disk at any point. If you want the file to be downloaded as well (as opposed to just being displayed in the browser), you'll have to set the content-disposition
header.
Here's an example of a server which will "download" the google logo. This is just using the standard http
module and not express, but it should work basically the same way:
var http = require('http');
http.createServer(function(req, res) {
var externalReq = http.request({
hostname: "www.google.com",
path: "/images/srpr/logo11w.png"
}, function(externalRes) {
res.setHeader("content-disposition", "attachment; filename=logo.png");
externalRes.pipe(res);
});
externalReq.end();
}).listen(8080);
If you want to use the request
module, it's even easier:
var http = require('http'),
request = require('request');
http.createServer(function(req, res) {
res.setHeader("content-disposition", "attachment; filename=logo.png");
request('http://google.com/images/srpr/logo11w.png').pipe(res);
}).listen(8080);
Note: The name of the file that the browser will save is set by the filename=
part of the content-disposition
header; in this case I set it to logo.png
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…