详解node.js 下载图片的 2 种方式
程序员文章站
2022-07-07 09:27:24
具体代码如下所示:
var request=require("request");
var fs=require("fs");
function downlo...
具体代码如下所示:
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 下载远程图片的实现代码,具体代码如下所示:
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;
总结
以上所述是小编给大家介绍的node.js 下载图片的 2 种方式,希望对大家有所帮助