nodejs 下载远程图片

var express = require('express');


var request = require('request');
var http = require('http');
var url = require('url');
var fs = require("fs");


var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
var url = "http://www.valu.cn/images/1.gif";
//request('http://www.valu.cn/images/1.gif').pipe(fs.createWriteStream('./public/upload/downImg/logonew.png'));


var req = http.get(url, function (res) {
var imgData = "";
res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
res.on("data", function (chunk) {
imgData += chunk;
});
res.on("end", function () {
fs.writeFile("./public/upload/downImg/logonew.png", imgData, "binary", function (err) {
if (err) {
console.log("保存失败");
}
console.log("保存成功");
});
});
res.on("error", function (err) {
console.log("请求失败");
});
});
req.on('error', function (err) {
console.log("请求失败2" + err.message);
});
res.render('index', {title: '首页2'});
});

module.exports = router;
posted @ 2017-02-16 23:27  威流  阅读(4126)  评论(0编辑  收藏  举报