iT邦幫忙

2

試著動態抓取資料夾內容並在網頁上顯示2 (feat.ChatGPT)

api
  • 分享至 

  • xImage
  •  

結論:試著讓網頁抓取電腦資料夾的圖片,成、功、了!

又問了幾次chatGPT,發現都會有CORS問題,被建議不要用Live Server而是用Express,讓html和api都在同一個伺服器上,不會有跨來源問題。
但現實是我還不知道Express是什麼…原來它也是伺服器,並藉由安裝nodemon讓它自動偵測檔案變更並重啟。

npm install -g nodemon  //安裝
nodemon server.js  //再啟動Express

接下來我又有個樸素的疑問,就是該怎麼看到頁面(之前只知道按VScode右下角Go Live的按鈕)
向chatGPT發問後,他說可以直接在瀏覽器輸入localhost網址,後面看是使用哪個port

http://localhost:3000  //舉例

順利在chrome打開預覽頁面後,按下F12看一下,果然console又有錯誤訊息:
前者似乎是因為執行的程式沒有放到正確的地方,導致瀏覽器找不到它,因此重新改了loadImages.js放的位置

Failed to load resource: the server responded with a status of 404 (Not Found)
Refused to execute script from 'http://localhost:3000/loadImages.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

後者從之前的經驗知道可以先放著不管

Unchecked runtime.lastError: The message port closed before a response was received.

最後執行的是以下三個檔案:

.html

<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Gallery</title>
  <style>
    .gallery {
      display: flex;
      flex-wrap: wrap;
    }
  
  </style>
</head>
<body>
  <h1>Portfolio</h1>
  <div class="gallery" id="gallery"></div>
  <div id="imageContainer"></div> <!--這行要under標題,才能顯示在標題下方 -->
  <script src="/loadImages.js"></script>

</body>
</html>

loadImages.js

async function loadImages() {
    const imageContainer = document.getElementById("imageContainer");

    try {
        const response = await fetch("http://localhost:3000/api/images"); // 取得後端 API 回傳的圖片列表
        const imageList = await response.json();

        imageList.forEach(imageName => {
            const img = document.createElement("img");
            img.src = `http://localhost:3000/images/${imageName}`;  // <-- 這裡要對應伺服器開放的 `/images/`
            img.alt = imageName;
            img.style.width = "150px";
            img.style.height = "150px";
            img.style.objectFit = "cover";
            imageContainer.appendChild(img);
        });
    } catch (error) {
        console.error("無法獲取圖片:", error);
    }
}
loadImages();

server.js

const express = require("express");
const app = express();
const path = require("path");
const fs = require("fs");

app.use(express.static("public")); // 讓 Express 直接提供 public 資料夾內的靜態檔案

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "public", "index.html"));
});

app.get("/api/images", (req, res) => {
    const imagesDir = path.join(__dirname, "public", "images"); // 你的圖片資料夾
    fs.readdir(imagesDir, (err, files) => {
        if (err) {
            return res.status(500).json({ error: "無法讀取資料夾" });
        }
        res.json(files.filter(file => file.endsWith(".jpg") || file.endsWith(".png"))); // 只回傳圖片
    });
});

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

然後就跑出來了。

現在遇到的問題,是目前圖片的設置如大小及裁切只能寫在loadImages.js裡,照理說要寫個css,但這就是明天努力的目標了。睡覺去!

雖然只是一小步,持續下去應該可以建出一個合意的作品集網站(舞
https://ithelp.ithome.com.tw/upload/images/20250202/20139352OQ3wPXKU2C.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言