JS 下載網絡圖片,並且修改圖片名稱


使用技術: NodeJS

gitHub地址: https://github.com/smallwhy/img-load-uptname

1、新建項目img-load-uptname

2、打開項目安裝cheerio

npm install cheerio

3、安裝request

npm install request

4、新建index.html

<html>
  <head>
    <meta charset="utf-8">
  </head>

  <body>
    <table border="1">
      <tr>
        <td>baidu-logo</td>
        <td>https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png</td>
      </tr>
      <tr>
        <td>baidu-bgimg-1</td>
        <td>https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin/1.jpg</td>
      </tr>
      <tr>
        <td>baidu-bgimg-2</td>
        <td>https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin/2.jpg</td>
      </tr>
    </table>
  </body>
</html>

5、新建load.js

const cheerio = require('cheerio');
var fs = require('fs');
var request = require('request');

// 讀取輸出到目錄的所有文件名
let imgNames = []
const files = fs.readdirSync('./images-2')
files.forEach(function (item, index) {
    imgNames.push(item);
});
console.log('images-2文件夾下的所有文件的文件名' + imgNames.join(','));


// 輸出圖片文件
fs.readFile("./index.html","utf-8",function(err,data){ // 讀取文件index.html
    if(err) {
      console.log("index.html loading is failed :"+err);
    }
    else{
        //返回index.html頁面
        var $ = cheerio.load(data); // data為index.html內容
        var tr_list = $('table tr');
        tr_list.each((index, item) => {
            var imgName = $(item).find('td').eq(0).text(); // 下載文件的最終命名
            var imgUrl = $(item).find('td').eq(1).text(); // 下載文件的URL
            var writeStream = fs.createWriteStream('./imgs/'+imgName + imgUrl.substring(imgUrl.lastIndexOf('.'))); // 創建寫入流
            var readStream = request(imgUrl); // 讀取流
            readStream.pipe(writeStream);
            readStream.on('end', function() { // 讀取文件
                console.log('文件下載成功');
            });
            readStream.on('error', function() {
                console.log("錯誤信息:" + err)
            });
            writeStream.on("finish", function() { // 寫入文件
                console.log("文件寫入成功");
                writeStream.end();
            });
        });
    }

});


6、新建存放下載圖片的文件夾imgs

7、命令行執行load.js

node load.js

最終結果:

項目目錄結構:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM