W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
使用 Moralis 時(shí),IPFS 支持開(kāi)箱即用。
您可以使用 ?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ù)會(huì)自動(dòng)固定。
您還可以直接從 JavaScript 上傳 JSON 對(duì)象,通過(guò)保存 base64 字符串,Moralis 將自動(dòng)從提供的 base64 創(chuàng)建緩沖區(qū):
const object = {
key: "value",
};
const file = new Moralis.File("file.json", {
base64: btoa(JSON.stringify(object)),
});
await file.saveIPFS();
通過(guò)上傳 base64,您還可以上傳其他 base64 編碼的文件,例如圖片(你可以使用?JS
?、?React
?來(lái)實(shí)現(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),
}
);
};
可以通過(guò)對(duì)公共網(wǎng)關(guān)的 GET 請(qǐng)求來(lái)檢索 IPFS 文件。 Moralis 網(wǎng)關(guān)的 URL 是:
例如,https://gateway.moralisipfs.com/ipfs/QmUfpsyqc4hwozotRo4woyi5fJqvfcej5GcFvKiWoY6xr6。 從瀏覽器獲取 IPFS 中的 JSON 文檔的函數(shù)可以編寫(xiě)如下:
async function fetchIPFSDoc(ipfsHash) {
const url = `https://gateway.moralisipfs.com/ipfs/${ipfsHash}`;
const response = await fetch(url);
return await response.json();
}
Moralis 公共 IPFS 網(wǎng)關(guān)用于:
Moralis 公共 IPFS 網(wǎng)關(guān)不適用于:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: