Moralis 文件

2022-05-12 14:33 更新

創(chuàng)建 Moralis.File

?Moralis.File? 允許您將應(yīng)用程序文件存儲(chǔ)在云中,否則這些文件會(huì)太大或太笨重而無(wú)法放入常規(guī)的 ?Moralis.Object?。 最常見(jiàn)的用例是存儲(chǔ)圖像,但您也可以將其用于文檔、視頻、音樂(lè)和任何其他二進(jìn)制數(shù)據(jù)。

?Moralis.File? 入門(mén)很容易。 有幾種方法可以創(chuàng)建文件。 第一個(gè)是使用 base64 編碼的字符串:

你可以使用?JS?、?React?來(lái)實(shí)現(xiàn)

const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
const file = new Moralis.File("myfile.txt", { base64: base64 });
const { saveFile } = useMoralisFile();

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

或者,您可以從字節(jié)值數(shù)組創(chuàng)建文件:

const bytes = [0xbe, 0xef, 0xca, 0xfe];
const file = new Moralis.File("myfile.txt", bytes);

Moralis 將根據(jù)文件擴(kuò)展名自動(dòng)檢測(cè)您上傳的文件類(lèi)型,但您可以使用第三個(gè)參數(shù)指定 Content-Type:

const file = new Moralis.File("myfile.zzz", fileData, "image/png");

在瀏覽器中

在瀏覽器中,您需要使用帶有文件上傳控件的 HTML 表單。 為此,請(qǐng)創(chuàng)建一個(gè)文件輸入標(biāo)簽,允許用戶從本地驅(qū)動(dòng)器中選擇要上傳的文件:

<input type="file" id="profilePhotoFileUpload" />

然后,在點(diǎn)擊處理程序或其他函數(shù)中,獲取對(duì)該文件的引用(你可以使用?JS?、?React?來(lái)實(shí)現(xiàn)):

const fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
  const file = fileUploadControl.files[0];
  const name = "photo.jpg";

  const moralisFile = new Moralis.File(name, file);
}
import { useState } from "react";
import { useMoralisFile } from "react-moralis";

function App() {
  const [fileTarget, setFileTarget] = useState("");
  const { saveFile } = useMoralisFile();

  const uploadFile = () => {
    saveFile("photo.jpg", fileTarget, {
      type: "image/png",
      onSuccess: (result) => console.log(result),
      onError: (error) => console.log(error),
    });
  };

  const fileInput = (e) => setFileTarget(e.target.files[0]);

  return (
    <div>
      <input type="file" onChange={fileInput} />
      <button onClick={uploadFile}>Call The Code</button>
    </div>
  );
}

export default App;

請(qǐng)注意,在此示例中,我們?yōu)槲募麨?nbsp;?photo.jpg?。 這里有兩點(diǎn)需要注意:

  • 您無(wú)需擔(dān)心文件名沖突。 每次上傳都有一個(gè)唯一的標(biāo)識(shí)符,因此上傳多個(gè)名為 ?photo.jpg? 的文件沒(méi)有問(wèn)題。
  • 為具有文件擴(kuò)展名的文件命名很重要。 這讓 Moralis 可以找出文件類(lèi)型并相應(yīng)地處理它。 因此,如果您要存儲(chǔ) PNG 圖像,請(qǐng)確保您的文件名以 ?.png? 結(jié)尾。

接下來(lái),您需要將文件保存到云端。 與 ?Moralis.Object? 一樣,您可以使用多種保存方法的變體,具體取決于適合您的回調(diào)和錯(cuò)誤處理類(lèi)型。

moralisFile.save().then(
  function () {
    // The file has been saved to Moralis.
  },
  function (error) {
    // The file either could not be read, or could not be saved to Moralis.
  }
);

在 Node.js 中

在 NodeJs 中,您可以獲取圖像或其他文件并將它們存儲(chǔ)為 ?Morales.File?:

const Moralis = require("moralis/node");
const request = require("request-promise");

const options = {
  uri: "https://bit.ly/2zD8fgm",
  resolveWithFullResponse: true,
  encoding: null, // <-- this is important for binary data like images.
};

request(options)
  .then((response) => {
    const data = Array.from(Buffer.from(response.body, "binary"));
    const contentType = response.headers["content-type"];
    const file = new Moralis.File("logo", data, contentType);
    return file.save();
  })
  .then((file) => console.log(file.url()))
  .catch(console.error);

在對(duì)象中

最后,在保存完成后,您可以將 ?Moralis.File? 與 ?Moralis.Object? 關(guān)聯(lián)起來(lái),就像任何其他數(shù)據(jù)一樣:

const jobApplication = new Moralis.Object("JobApplication");
jobApplication.set("applicantName", "Joe Smith");
jobApplication.set("applicantResumeFile", moralisFile);
jobApplication.save();

如果您在云代碼中保存文件,則必須在保存對(duì)象時(shí)提供 ?MasterKey?。 例子:

jobApplication.save(null, { useMasterKey: true });

檢索文件內(nèi)容

如何最好地檢索文件內(nèi)容取決于您的應(yīng)用程序的上下文。 由于跨域請(qǐng)求問(wèn)題,最好讓瀏覽器為您完成工作。 通常,這意味著將文件的 URL 渲染到 DOM 中。 在這里,我們使用 jQuery 在頁(yè)面上渲染上傳的個(gè)人資料照片:

const profilePhoto = profile.get("photoFile");
$("profileImg")[0].src = profilePhoto.url();

如果您想在云代碼中處理文件的數(shù)據(jù),您可以使用我們的 HTTP 網(wǎng)絡(luò)庫(kù)檢索該文件:

Moralis.Cloud.httpRequest({ url: profilePhoto.url() }).then(function (
  response
) {
  // The file contents are in response.buffer.
});

刪除文件

您可以使用 ?destroy ?方法刪除對(duì)象引用的文件。 刪除文件需要主密鑰:

const profilePhoto = profile.get("photoFile");
await profilePhoto.destroy({ useMasterKey: true });

添加元數(shù)據(jù)和標(biāo)簽

向文件添加元數(shù)據(jù)和標(biāo)簽允許您向存儲(chǔ)在存儲(chǔ)解決方案(即 AWS S3)中的文件添加額外的數(shù)據(jù)位。

注意:并非所有存儲(chǔ)適配器都支持元數(shù)據(jù)和標(biāo)簽。 檢查您正在使用的存儲(chǔ)適配器的文檔以了解兼容性。

你可以使用?JS?、?React?來(lái)實(shí)現(xiàn)

// Init with metadata and tags
const metadata = { createdById: "some-user-id" };
const tags = { groupId: "some-group-id" };
const file = new Moralis.File(
  "myfile.zzz",
  fileData,
  "image/png",
  metadata,
  tags
);

// Add metadata and tags
const file = new Moralis.File("myfile.zzz", fileData, "image/png");
file.addMetadata("createdById", "some-user-id");
file.addTag("groupId", "some-group-id");
const metadata = { createdById: "some-user-id" };
const tags = { groupId: "some-group-id" };
saveFile(
  "myfile.png",
  { fileData },
  {
    type: "image/png",
    metadata,
    tags,
    onSuccess: (result) => console.log(result.ipfs()),
    onError: (error) => console.log(error),
  }
);


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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)