NodeJs 遍历文件夹内容 上传到服务器.并输出上传记录文件
1 var path = require('path'); 2 var glob = require('glob') 3 var fs = require('fs'); 4 var Promise = require('bluebird'); 5 var readdir = Promise.promisify(fs.readdir); 6 var rename = Promise.promisify(fs.rename); 7 var readFile = Promise.promisify(fs.readFile); 8 var writeFile = Promise.promisify(fs.writeFile); 9 var request = Promise.promisify(require('request')); 10 var projectinfo = require('./build/projectinfo'); 11 const jsonname = "./uploadimg/uploadimg.txt"; 12 13 function updateFile(filepath, dir) { 14 var _fileName = path.join(projectinfo.updatesrc, filepath.split('/').slice(2).join('/')); 15 let tmp_fileName = filepath.split('/').slice(2).join('/'); 16 _fileName = _fileName.split('\\').join('/'); 17 console.log(tmp_fileName); 18 19 fs.readFile(jsonname, function(err, data) { 20 if (err) { 21 fs.createWriteStream(jsonname) 22 } 23 }); 24 25 var formData = { 26 filename: _fileName, 27 file: fs.createReadStream(filepath) 28 }; 29 var _options = { 30 method: 'POST', 31 uri: 'http://***.***.***/upload/***?', 32 qs: { 33 guid: '***', 34 rand: 1, 35 time: 1, 36 platform: 'server' 37 }, 38 formData: formData 39 } 40 request(_options) 41 .then(function(res) { 42 var _body = JSON.parse(res.body); 43 if (!_body.errno) { 44 var resinfo = JSON.parse(res.body); 45 console.log(resinfo); 46 writeJson(tmp_fileName, resinfo.data.url); 47 } 48 }) 49 .catch(function(err) { 50 console.log(err) 51 }) 52 } 53 54 55 glob.sync('./uploadimg/*.*').forEach(function(entry) { 56 basename = path.basename(entry) 57 if (/(png)$/.test(basename) || /(jpg)$/.test(basename)) { 58 //console.log("需要上传的文件:\n" + entry + "\n") 59 updateFile(entry) 60 } 61 }) 62 63 function writeJson(_name, _val) { 64 var _str = _name + " : " + _val + "\n"; 65 fs.appendFile(jsonname, _str, function(err) { 66 if (err) { 67 console.log("写入失败:" + obj); 68 } 69 }); 70 71 }