我正在尝试编写一个简单的图像代理服务器(如果这不是正确的措辞,请随时纠正我。)
用例:
这是我目前的版本。它似乎服务于损坏的图像文件(并在通过Web浏览器打开时打开下载提示...)。
更新:以下工作版本。
var restify = require("restify");
var http = require("http");
var request = require("request");
var server = restify.createServer();
server.listen(1234, function() {
console.log("%s listening at %s", server.name, server.url);
});
server.get("/image", getImage);
function getImage(req, res, next) {
var imageURL = "http://png-5.findicons.com/files/icons/409/witchery/128/cat.png";
http.get(imageURL, function(response) {
var imageSize = parseInt(response.header("Content-Length"));
var imageBuffer = new Buffer(imageSize);
var bytes = 0;
response.setEncoding("binary");
response.on("data", function(chunk) {
imageBuffer.write(chunk, bytes, "binary");
bytes += chunk.length;
});
response.on("end", function() {
console.log("Download complete, sending image.");
res.setHeader("Content-Type", "image/png");
res.send(imageBuffer);
return next();
});
}
答案 0 :(得分:13)
为什么不直接管道?
app.get('/:path', function(req, res) {
request.get('www.imgserver.com/images/' + path).pipe(res);
}
答案 1 :(得分:4)
好的,我最终得到了它:)
http.get(imageURL, function(response) {
var imageSize = parseInt(response.header("Content-Length"));
var imageBuffer = new Buffer(imageSize);
var bytes = 0;
response.setEncoding("binary");
response.on("data", function(chunk) {
imageBuffer.write(chunk, bytes, "binary");
bytes += chunk.length;
});
response.on("end", function() {
console.log("Download complete, sending image.");
res.setHeader("Content-Type", "image/png");
res.send(imageBuffer);
return next();
});
}