今天主要和大家分享两种node.js下载图片的方法,话不多说直接上代码:
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);
}
})
}
})
}
下面是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;
好啦,以上便是nodejs下载图片,这两种方式你会吗的全部分享,更多内容干货可关注慕课其他相关文章~
共同学习,写下你的评论
评论加载中...
作者其他优质文章