· Nacho Coll · Guides  · 12 分鐘閱讀

NFT 元數據存儲:NFT 創作者的 IPFS 完整指南

在 IPFS 上存儲 NFT 元數據的逐步指南。包含 ERC-721 tokenURI 模式以及 Python 和 JavaScript 範例。

在 IPFS 上存儲 NFT 元數據的逐步指南。包含 ERC-721 tokenURI 模式以及 Python 和 JavaScript 範例。

建立 NFT 不僅僅需要部署智能合約 — 您還需要為元數據和資產提供可靠的去中心化儲存。這份完整指南將透過業界最佳實踐,逐步引導您完成在 IPFS 上儲存 NFT 元數據的流程,並附有針對 Python 和 JavaScript 開發者的完整程式碼範例。

IPFS Ninja

為什麼選擇 IPFS 進行 NFT 元數據存儲?

傳統網路託管會為 NFT 專案帶來中心化風險。當元數據存放在傳統伺服器上時,如果託管服務當機或變更 URL,NFT 可能會「損壞」。IPFS(InterPlanetary File System)透過提供以下功能解決了這個問題:

  • 不可變的內容定址:每個檔案都會獲得一個永不改變的唯一 Content Identifier (CID)
  • 去中心化儲存:內容存在於全球多個節點上
  • 加密驗證:透過內容雜湊保證檔案完整性
  • 面向未來的 URL:IPFS 連結可無限期運作,保護長期價值

如需更深入了解 IPFS 基礎知識,請查看我們關於什麼是 IPFS pinning 的指南。

了解 ERC-721 元數據結構

ERC-721 標準定義了 NFT 元數據的結構方式。您的智能合約的 tokenURI 函式會回傳一個指向 JSON 元數據的 URL,遵循以下模式:

{
  "name": "My Amazing NFT #1",
  "description": "A unique digital artwork showcasing...",
  "image": "ipfs://QmYourImageCIDHere",
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Blue"
    },
    {
      "trait_type": "Rarity",
      "value": "Common"
    }
  ],
  "external_url": "https://yourproject.com/token/1"
}

元數據關鍵欄位

  • name:在錢包和市場中顯示的 NFT 標題
  • description:關於 NFT 的詳細資訊
  • image:指向主要視覺資產的 IPFS URL
  • attributes:基於特徵的屬性,用於篩選和稀有度計算
  • external_url:指向附加內容或您的專案網站的可選連結

逐步 IPFS NFT 存儲流程

步驟 1:準備您的資產和元數據

在上傳任何內容之前,先組織您的檔案:

  1. 主要資產:圖片、影片或其他主要內容
  2. 元數據檔案:描述每個 NFT 的 JSON 檔案
  3. 集合元數據:可選的集合級別資訊

步驟 2:上傳資產到 IPFS

首先上傳您的主要 NFT 資產(圖片、影片等)以取得它們的 IPFS CID。您將在 JSON 元數據檔案中參照這些 CID。

以下是使用 Python 上傳圖片的方法:

import requests
import base64
import json

def upload_image_to_ipfs(image_path, api_key):
    """Upload an image file to IPFS and return its CID"""
    
    # Read and encode image
    with open(image_path, 'rb') as f:
        image_data = base64.b64encode(f.read()).decode('utf-8')
    
    # Prepare upload payload
    payload = {
        "content": image_data,
        "description": f"NFT Asset: {image_path}"
    }
    
    headers = {
        "Content-Type": "application/json",
        "X-Api-Key": api_key
    }
    
    # Upload to IPFS.NINJA
    response = requests.post(
        "https://api.ipfs.ninja/upload/new",
        headers=headers,
        json=payload
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ Image uploaded successfully!")
        print(f"CID: {result['cid']}")
        print(f"IPFS URL: {result['uris']['ipfs']}")
        print(f"Gateway URL: {result['uris']['url']}")
        return result['cid']
    else:
        print(f"❌ Upload failed: {response.text}")
        return None

# Example usage
API_KEY = "bws_1234567890abcdef1234567890abcdef"  # Replace with your actual key
image_cid = upload_image_to_ipfs("my-nft-artwork.png", API_KEY)

步驟 3:建立並上傳元數據 JSON

取得資產 CID 後,建立元數據 JSON 檔案並上傳:

def create_and_upload_metadata(name, description, image_cid, attributes, api_key):
    """Create NFT metadata JSON and upload to IPFS"""
    
    # Create metadata object
    metadata = {
        "name": name,
        "description": description,
        "image": f"ipfs://{image_cid}",
        "attributes": attributes
    }
    
    # Convert to JSON string and encode
    metadata_json = json.dumps(metadata, indent=2)
    metadata_b64 = base64.b64encode(metadata_json.encode('utf-8')).decode('utf-8')
    
    # Upload metadata
    payload = {
        "content": metadata_b64,
        "description": f"NFT Metadata: {name}",
        "metadata": {
            "contentType": "application/json",
            "nftTokenId": name.split('#')[1] if '#' in name else "1"
        }
    }
    
    headers = {
        "Content-Type": "application/json",
        "X-Api-Key": api_key
    }
    
    response = requests.post(
        "https://api.ipfs.ninja/upload/new",
        headers=headers,
        json=payload
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ Metadata uploaded successfully!")
        print(f"Metadata CID: {result['cid']}")
        return result['cid']
    else:
        print(f"❌ Metadata upload failed: {response.text}")
        return None

# Example usage
attributes = [
    {"trait_type": "Background", "value": "Cosmic Blue"},
    {"trait_type": "Eyes", "value": "Laser"},
    {"trait_type": "Rarity", "value": "Epic"}
]

metadata_cid = create_and_upload_metadata(
    name="Cosmic Warrior #001",
    description="A fierce warrior from the distant galaxies, wielding the power of stars.",
    image_cid=image_cid,
    attributes=attributes,
    api_key=API_KEY
)

步驟 4:JavaScript 實作

對於網頁應用程式或 Node.js 專案,以下是 JavaScript 的對應實作:

class NFTStorage {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseUrl = 'https://api.ipfs.ninja';
    }
    
    async uploadFile(fileContent, description) {
        const payload = {
            content: fileContent, // base64 encoded
            description: description
        };
        
        const response = await fetch(`${this.baseUrl}/upload/new`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Api-Key': this.apiKey
            },
            body: JSON.stringify(payload)
        });
        
        if (!response.ok) {
            throw new Error(`Upload failed: ${response.statusText}`);
        }
        
        return await response.json();
    }
    
    async uploadImageFromFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = async (e) => {
                try {
                    const base64Content = e.target.result.split(',')[1]; // Remove data:image/...;base64, prefix
                    const result = await this.uploadFile(base64Content, `NFT Image: ${file.name}`);
                    resolve(result.cid);
                } catch (error) {
                    reject(error);
                }
            };
            reader.readAsDataURL(file);
        });
    }
    
    async uploadMetadata(name, description, imageCid, attributes = []) {
        const metadata = {
            name,
            description,
            image: `ipfs://${imageCid}`,
            attributes
        };
        
        const metadataJson = JSON.stringify(metadata, null, 2);
        const base64Metadata = btoa(metadataJson);
        
        const result = await this.uploadFile(base64Metadata, `NFT Metadata: ${name}`);
        return result.cid;
    }
}

// Usage example
const storage = new NFTStorage('bws_1234567890abcdef1234567890abcdef'); // Replace with your key

// Upload process
async function createNFT() {
    try {
        // Assuming you have a file input element
        const fileInput = document.getElementById('nft-image');
        const imageFile = fileInput.files[0];
        
        console.log('Uploading image...');
        const imageCid = await storage.uploadImageFromFile(imageFile);
        console.log(`Image uploaded: ${imageCid}`);
        
        console.log('Uploading metadata...');
        const metadataCid = await storage.uploadMetadata(
            'Galaxy Explorer #042',
            'A mysterious explorer traversing the cosmic void.',
            imageCid,
            [
                { trait_type: 'Class', value: 'Explorer' },
                { trait_type: 'Galaxy', value: 'Andromeda' },
                { trait_type: 'Rarity', value: 'Legendary' }
            ]
        );
        
        console.log(`Metadata uploaded: ${metadataCid}`);
        console.log(`Token URI: ipfs://${metadataCid}`);
        
    } catch (error) {
        console.error('Upload failed:', error);
    }
}

在智能合約中實作 tokenURI

當您的元數據上傳到 IPFS 後,在您的 ERC-721 合約中實作 tokenURI 函式:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyNFTCollection is ERC721, Ownable {
    mapping(uint256 => string) private _tokenURIs;
    string private _baseTokenURI;
    
    constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
    
    function setTokenURI(uint256 tokenId, string memory uri) external onlyOwner {
        require(_exists(tokenId), "Token does not exist");
        _tokenURIs[tokenId] = uri;
    }
    
    function setBaseURI(string memory baseURI) external onlyOwner {
        _baseTokenURI = baseURI;
    }
    
    function tokenURI(uint256 tokenId) public view virtual override returns (string) {
        require(_exists(tokenId), "Token does not exist");
        
        string memory _tokenURI = _tokenURIs[tokenId];
        
        // Return specific token URI if set
        if (bytes(_tokenURI).length > 0) {
            return _tokenURI;
        }
        
        // Fall back to base URI + token ID pattern
        if (bytes(_baseTokenURI).length > 0) {
            return string(abi.encodePacked(_baseTokenURI, tokenId.toString()));
        }
        
        return "";
    }
    
    function mintWithURI(address to, uint256 tokenId, string memory uri) external onlyOwner {
        _mint(to, tokenId);
        _tokenURIs[tokenId] = uri;
    }
}

大型集合的批次操作

對於大型 NFT 集合,批次操作可以節省時間和 gas 成本:

def batch_upload_collection(collection_data, api_key):
    """Upload an entire NFT collection in batches"""
    
    print(f"Starting batch upload of {len(collection_data)} NFTs...")
    results = []
    
    for i, nft_data in enumerate(collection_data):
        print(f"Processing NFT {i+1}/{len(collection_data)}: {nft_data['name']}")
        
        try:
            # Upload image
            image_cid = upload_image_to_ipfs(nft_data['image_path'], api_key)
            
            if image_cid:
                # Upload metadata
                metadata_cid = create_and_upload_metadata(
                    name=nft_data['name'],
                    description=nft_data['description'],
                    image_cid=image_cid,
                    attributes=nft_data['attributes'],
                    api_key=api_key
                )
                
                if metadata_cid:
                    results.append({
                        'token_id': i + 1,
                        'name': nft_data['name'],
                        'image_cid': image_cid,
                        'metadata_cid': metadata_cid,
                        'token_uri': f"ipfs://{metadata_cid}"
                    })
                    
        except Exception as e:
            print(f"❌ Error processing {nft_data['name']}: {e}")
    
    print(f"✅ Batch upload complete! {len(results)} NFTs processed successfully.")
    return results

# Example collection data
collection_data = [
    {
        'name': 'Cosmic Warrior #001',
        'description': 'A fierce warrior from distant galaxies.',
        'image_path': 'images/warrior_001.png',
        'attributes': [
            {'trait_type': 'Class', 'value': 'Warrior'},
            {'trait_type': 'Rarity', 'value': 'Epic'}
        ]
    },
    # Add more NFTs...
]

results = batch_upload_collection(collection_data, API_KEY)

NFT 元數據存儲的最佳實踐

1. 使用描述性檔案名稱

上傳到 IPFS 時,使用有意義的描述以協助組織:

payload = {
    "content": base64_content,
    "description": f"Collection: {collection_name} | Token: {token_id} | Type: {file_type}"
}

2. 實作適當的錯誤處理

始終優雅地處理上傳失敗:

import time

def upload_with_retry(upload_function, max_retries=3, delay=2):
    """Upload with exponential backoff retry logic"""
    
    for attempt in range(max_retries):
        try:
            return upload_function()
        except Exception as e:
            if attempt == max_retries - 1:
                raise e
            print(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay} seconds...")
            time.sleep(delay)
            delay *= 2  # Exponential backoff

3. 驗證元數據結構

確保您的元數據符合標準:

def validate_metadata(metadata):
    """Validate NFT metadata structure"""
    required_fields = ['name', 'description', 'image']
    
    for field in required_fields:
        if field not in metadata:
            raise ValueError(f"Missing required field: {field}")
    
    if not metadata['image'].startswith('ipfs://'):
        raise ValueError("Image must be an IPFS URL")
    
    if 'attributes' in metadata:
        for attr in metadata['attributes']:
            if 'trait_type' not in attr or 'value' not in attr:
                raise ValueError("Invalid attribute structure")
    
    return True

選擇合適的 IPFS Pinning 服務

為您的 NFT 專案選擇 IPFS pinning 服務時,請考慮:

  • 可靠性:保證的正常運行時間以提供長期儲存
  • 效能:全球快速的檢索速度
  • 價格:適合您集合規模的成本效益
  • 功能:API 能力、分析和開發者工具

如需詳細的 pinning 服務比較,請閱讀我們的 IPFS Ninja vs Pinata 比較和我們的最佳 IPFS pinning 服務指南。

進階功能:自訂閘道和分析

IPFS Ninja 為專業 NFT 專案提供額外功能:

自訂閘道配置

為您的集合建立品牌化的 IPFS 閘道:

// Access your NFT through a custom gateway
const customGateway = 'https://my-collection.gw.ipfs.ninja';
const nftUrl = `${customGateway}/ipfs/${metadataCid}`;

上傳分析

透過儀表板分析監控您的 NFT 儲存使用情況和存取模式,幫助您了解集合效能並最佳化儲存成本。

常見問題排除

元數據無法載入

  • 確認 IPFS URL 使用 ipfs:// 協定
  • 檢查元數據 JSON 是否有效
  • 確保 pinning 服務正在維護內容

圖片未顯示

  • 確認元數據中的圖片 CID 正確
  • 在 IPFS 閘道測試圖片 URL
  • 確認圖片檔案格式與網路相容

Gas 估算錯誤

  • 確保 tokenURI 函式回傳有效字串
  • 檢查元數據中的循環參照
  • 在 minting 之前驗證所有 IPFS CID

監控和維護您的 NFT 儲存

部署集合後:

  1. 定期健康檢查:驗證元數據和圖片仍可存取
  2. 備份重要 CID:保留所有已上傳內容識別碼的記錄
  3. 監控分析:追蹤存取模式和儲存使用情況
  4. 規劃擴充:考慮隨著集合成長升級您的 pinning 服務

如需更多關於以程式化方式管理上傳的詳細資訊,請參閱我們的 IPFS upload API 教學

結論

將 NFT 元數據儲存在 IPFS 上可確保您的數位資產長期保持可存取性和價值。透過遵循本指南,您已學會:

  • 建構符合 ERC-721 的元數據
  • 使用 Python 和 JavaScript 上傳資產和元數據
  • 實作適當的 tokenURI 函式
  • 處理大型集合的批次操作
  • 套用生產部署的最佳實踐

IPFS 的去中心化架構與可靠的 pinning 服務相結合,為經得起時間考驗的成功 NFT 專案奠定了基礎。

準備好開始 pinning 了嗎? 建立免費帳戶 — 50 個檔案、1 GB 儲存空間、2 GB 頻寬/月。無需信用卡。

返回部落格