具體代碼如下所示:
var request=require("request"); var fs=require("fs"); function download1(url,filename,fn){ request(url).pipe(fs.createWriteStream(filename).on("close",function(err,res){ if(err){ console.log(err); }else{ fn&&fn(); } })) } function download2(url,filename,fn){ request.get({uri:url, encoding:'binary'},function(err,res){ if(!err){ fs.writeFile(filename,res.body,"binary",function(err,res){ if(!err){ fn&&fn(); }else{ console.log(err); } }) } }) }
ps:下面看下nodejs 下載遠程圖片的實現(xiàn)代碼,具體代碼如下所示:
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"); //一定要設(shè)置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;
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com