node拉取远程图片并存储本地

74 阅读1分钟

app.get('/api/test1', async (req, res, next) => { console.log('I am the router middleware => /api/test1')

let startTime = '2019-01-01';

const downImg = async (month) => {

// 下载图片
const sss = await axios({
  method: 'post',
  url: 'http://www.didano.cn/wechat_v2//base/StudentPersonalCenter/post/findRawTemperature/389604/' + month + '?from=xiaonuo-vue&oriId=gh_98d50f853359&sid=1294&stoken=ZTg4MGMzMzdiNTEyOGI2MmZmNjRkMGExYjQ4MDFlODgjMTY5NTYzNDcwOTY4MCMzMTUzNjAwMCNNVEk1TkE9PQ%3D%3D',
});



const imgList = sss.data.data.list.map(item => {
  return {
    imgUrl: item.orgImgUrl.split("?")[0],
    name: moment(item.created).format("YYYYMMDD") + '.jpg'
  }
})
if(!imgList.length){
  return
}
const dirName = month;
if (fs.existsSync(dirName)) {
  console.log("存在了文件加" + dirName)
} else {
  fs.mkdirSync(dirName);
}
const dir = 'img'

imgList.forEach(item => {
  const { imgUrl, name } = item;
  let stream = fs.createWriteStream(path.join(dirName, name));
  request(imgUrl).pipe(stream).on("close", function (err) {
    console.log("文件" + name + "下载完毕");
  });
});

} while (moment(startTime).isBefore('2023-10-01')) { const str = moment(startTime).format('YYYY-MM'); downImg(str) startTime = moment(startTime).add(1, 'M').format('YYYY-MM-01') }

// const url = 'image-didanuo.oss-cn-shenzhen.aliyuncs.com/upload/stud…'; // const fileName = "1111.jpg" // const dir = 'img' // console.log('------------------------------------------------') // console.log(url) // console.log(fileName) // console.log(dir) // let stream = fs.createWriteStream(path.join(dir, fileName)); // request(url).pipe(stream).on("close", function (err) { // console.log("文件" + fileName + "下载完毕"); // });

// const dirname = 'uploadImages' // const hostdir = "./public/mito/" // function mkdirSync(dirname) { // if (fs.existsSync(dirname)) { // return true; // } else { // if (mkdirSync(path.dirname(dirname))) { // fs.mkdirSync(dirname); // return true; // } // } // return false // }

// function downloadUrl(urlList) { // for (const url of urlList) { // const first = url.indexOf(dirname) // const last = url.lastIndexOf('/') // if (first > 0 && last > 0) { // const name = url.substr(last + 1) // const dir = url.substr(first, last - first) // const dstpath = hostdir + dir + '/' + name // if (name.length && dir.length && !fs.existsSync(dstpath)) { // if (mkdirSync(hostdir + dir)) { // console.log(dstpath) // request(url).pipe(fs.createWriteStream(dstpath)) // } // } // } // } // }

res.status(200).send('hello') })