node JS遍历上传本地文件

本文介绍了一个使用Node.js实现的批量图片读取及上传的示例代码。该示例通过遍历指定目录下的所有文件,将每张图片转换为Base64字符串,并通过HTTP POST请求发送到本地服务器进行上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**

* Created by lizhen on 2017/9/10.
*/
var fs = require('fs'),
path = require('path');
let imgMap = [];
function travel(dircallback) {
fs.readdirSync(dir).forEach(function (file) {
var pathname = '/Users/lizhen/Desktop/index/finlink-lettrron-bgsystem/影像信息/' + file;
var imageBuf = fs.readFileSync(pathname);
var base64ImageBuf = imageBuf.toString("base64");
imgMap.push({'name': file'base64': base64ImageBuf});
});
}
travel('影像信息');

// console.log(imgMap);
var http = require('http')
var options = {
hostname'localhost',
port8010,
path'/resources/upload/base64image',
method'POST',
headers:{
"Content-Type"'application/json',
}
};
let allImg = [];
let nodeHttpImg function (i) {
console.log(i)
var req = http.request(optionsfunction (res) {
res.setEncoding('utf8');
res.on('data'function (chunk) {
console.log(chunk)
let data = JSON.parse(chunk)
if(data.success){
allImg.push({'name':imgMap[i].name,'imgUrl':data.data.file})
}
});
res.on('end',function() {
if(i<imgMap.length-1){
nodeHttpImg(i+1)
}

console.log(allImg.length)
});
});
req.on('error'function (e) {
console.log('problem with request: ' + e.message);
});

let data = {'file':imgMap[i].base64}
req.write(JSON.stringify(data));
req.end()
}

nodeHttpImg(0);
// write data to reques body

效果


有问题欢迎评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值