from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import urlparse, unquote PHOTO_FOLDER = Path(r"C:\Users\myyuh\Desktop\PhotoBoothPhotos").resolve() HOST = "0.0.0.0" PORT = 8080 class PhotoHandler(BaseHTTPRequestHandler): def do_GET(self): name = unquote(urlparse(self.path).path).lstrip("/") print("收到請求:", repr(name)) # 只允許讀取資料夾內的 JPG 照片 if not name.lower().endswith((".jpg", ".jpeg")) or "/" in name or "\\" in name: self.send_error(404, "Photo not found") return photo = (PHOTO_FOLDER / name).resolve() if photo.parent != PHOTO_FOLDER or not photo.is_file(): print("找不到檔案:", photo) self.send_error(404, "Photo not found") return try: data = photo.read_bytes() self.send_response(200) self.send_header("Content-Type", "image/jpeg") self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) print("成功傳送:", photo, len(data), "bytes") except OSError as e: print("讀取失敗:", repr(e)) self.send_error(500, "Cannot read photo") def log_message(self, format, *args): print("[HTTP]", format % args) if __name__ == "__main__": print("照片資料夾:", PHOTO_FOLDER) print("資料夾存在:", PHOTO_FOLDER.is_dir()) print("test.jpg 存在:", (PHOTO_FOLDER / "test.jpg").is_file()) server = ThreadingHTTPServer((HOST, PORT), PhotoHandler) print("伺服器啟動於 port", PORT) try: server.serve_forever() except KeyboardInterrupt: print("停止伺服器") finally: server.server_close()