Moralis IPFS

2022-05-12 14:38 更新

保存文件

使用 Moralis 時,IPFS 支持開箱即用。

您可以使用 ?saveIPFS()? 方法上傳文件(最大文件大小為 1 GB)。

// Save file input to IPFS
const data = fileInput.files[0];
const file = new Moralis.File(data.name, data);
await file.saveIPFS();

//console.log(file.ipfs(), file.hash())

// Save file reference to Moralis
const jobApplication = new Moralis.Object("Applications");
jobApplication.set("name", "Satoshi");
jobApplication.set("resume", file);
await jobApplication.save();

// Retrieve file
const query = new Moralis.Query("Applications");
query.equalTo("name", "Satoshi");
query.find().then(function ([application]) {
  const ipfs = application.get("resume").ipfs();
  const hash = application.get("resume").hash();
  console.log("IPFS url", ipfs);
  console.log("IPFS hash", hash);
});

數(shù)據(jù)會自動固定。

保存對象

您還可以直接從 JavaScript 上傳 JSON 對象,通過保存 base64 字符串,Moralis 將自動從提供的 base64 創(chuàng)建緩沖區(qū):

const object = {
  key: "value",
};
const file = new Moralis.File("file.json", {
  base64: btoa(JSON.stringify(object)),
});
await file.saveIPFS();

通過上傳 base64,您還可以上傳其他 base64 編碼的文件,例如圖片(你可以使用?JS?、?React?來實現(xiàn))。

const image = "data:image/png;base64,iVBORw0KGgoAAA....";
const file = new Moralis.File("image.png", { base64: image });
await file.saveIPFS();
const { saveFile } = useMoralisFile();

const uploadFile = () => {
  const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
  saveFile(
    "myfile.txt",
    { base64 },
    {
      type: "base64",
      saveIPFS: true,
      onSuccess: (result) => console.log(result.ipfs()),
      onError: (error) => console.log(error),
    }
  );
};

通過公用網(wǎng)關(guān)獲取文件

可以通過對公共網(wǎng)關(guān)的 GET 請求來檢索 IPFS 文件。 Moralis 網(wǎng)關(guān)的 URL 是:

例如,https://gateway.moralisipfs.com/ipfs/QmUfpsyqc4hwozotRo4woyi5fJqvfcej5GcFvKiWoY6xr6。 從瀏覽器獲取 IPFS 中的 JSON 文檔的函數(shù)可以編寫如下:

async function fetchIPFSDoc(ipfsHash) {
  const url = `https://gateway.moralisipfs.com/ipfs/${ipfsHash}`;
  const response = await fetch(url);
  return await response.json();
}

公共網(wǎng)關(guān)用例

Moralis 公共 IPFS 網(wǎng)關(guān)用于:

  • 在通過 Moralis 上傳的網(wǎng)站上顯示內(nèi)容

Moralis 公共 IPFS 網(wǎng)關(guān)不適用于:

  • 運行從 IPFS 下載內(nèi)容的腳本。 Moralis 公共網(wǎng)關(guān)有一個用于防止濫用的 JS Challenge 阻止腳本。 如果您的用例要求您運行腳本下載大量 IPFS 數(shù)據(jù),我們推薦 Infura 或 Pinata。
  • 訪問 IPFS 上未通過 Moralis 上傳的文件。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號