☁️
Züs
  • About Züs
  • Concepts
    • Architecture
      • Mining on the Züs Blockchain
        • Onboarding a New Miner or Sharder
        • Block Production Protocol
        • Block Finalization
        • Merkle Patricia Trees(MPT) and Recovery
        • View Change and Distributed Key Generation(DKG)
      • Payment
      • Storage
      • Token Bridge Protocol
      • Resources
    • Tokenomics
      • Staking Process
      • Block Rewards
      • Delegation
    • Store
    • Earn
    • Build
    • NFT
  • Resources
    • Whitepapers
      • Tokenomics Paper
      • Architecture Paper
      • Storage Paper
    • Patents
      • NON-FUNGIBLE TOKEN BLOCKCHAIN PROCESSING
      • FREE STORAGE PROTOCOL FOR BLOCKCHAIN PLATFORM
      • TRANSFERRING CONTENT VIA PROXY RE-ENCRYPTION
      • STREAMING CONTENT VIA BLOCKCHAIN TECHNOLOGY
      • SPLIT-KEY WALLET ACCESS BETWEEN BLOCKCHAINS
      • ENFORCING SECURITY PARAMETERS SPECIFIED BY AN OWNER ON A BLOCKCHAIN PLATFORM
      • CLIENT AUTHENTICATION USING SPLIT KEY SIGNING ON A BLOCKCHAIN PLATFORM
      • BLOCKCHAIN CONTENT PURCHASING PROTOCOL
      • BLOCKCHAIN BASED PRIVACY COMPLIANCE PLATFORM
      • SYSTEMS AND METHODS OF SELF-ADMINISTERED PROTOCOLS ON A BLOCKCHAIN PLATFORM
      • SYSTEMS AND METHODS OF AGGREGATE SIGNING OF DIGITAL SIGNATURES ON MULTIPLE MESSAGES SIMULTANEOUSLY U
      • SYSTEMS AND METHODS OF BLOCKCHAIN PLATFORM FOR AUTOMATED ASSET BASED PROVISIONING OF RESOURCES
      • SYSTEMS AND METHODS OF SELF-FORKING BLOCKCHAIN PROTOCOL
      • SYSTEMS AND METHODS OF SUSTAINABILITY PROTOCOL USING DISTRIBUTED BLOCKCHAIN APPLICATION WITH IoT SEN
      • SYSTEMS AND METHODS OF BLOCKCHAIN PLATFORM FOR DISTRIBUTED APPLICATIONS
  • API Reference
    • Endpoints
      • Block
      • Client
      • Connection
      • DNS
      • File
      • Smart Contracts
      • Blobber Stats
      • Transactions
      • Miners and Sharders
        • Stats
        • State
        • Diagnostics
        • Configuration
        • Smart Contract State
        • Smart Contract Stats
        • Chain Stats
  • Hackathon
    • Register to Hackathon
      • How to Add Members to Hackathon Team
    • Repos
    • Documentation
  • Products
    • Bolt
      • Get Started
      • Stake
      • Activity
      • Buy ZCN
      • Sell ZCN
      • Send Tokens
      • Receive Tokens
      • Settings
        • Manage Profile
        • Wallet
        • Read Pool
      • Troubleshooting
    • Vult
      • Sign Up
      • Upload File
      • Upload an Encrypted File
      • Upload a File to a Folder
      • Share a Uploaded File
      • Move a Uploaded File
      • Delete a File
      • Make File Available Offline
      • Troubleshooting
    • Atlus
      • Dashboard Overview
      • Service Providers
      • Charts
        • Market Charts
        • Network Charts
        • Storage Charts
        • Züs Explainer
      • Blockchain
      • Server Map
    • Blimp
      • Sign Up
        • Buy ZCN for Storage
      • Use Blimp as Direct Storage
      • Use Blimp as S3 Server
        • S3 Operations
      • Use Blimp for Cloud Migration
      • Manage Allocations
        • Extend Size
        • Extend Duration
        • Add Blobber
        • Replace Blobber
        • Make allocation Immutable
        • Freeze Allocation
        • Cancel Allocation
    • Chimney
      • Get Started
      • Deploy Blobber on Own Server
      • Deploy Blobber on Rented Server
      • Stake Blobber
      • Add Blobber
      • Monitor Blobbers
      • Visualize Blobber Logs
      • View Blobber Rank
    • Chalk
      • Sign Up
      • Create NFT Collection
        • Buy ZCN for NFT via ERC token
        • Buy ZCN for NFT via Credit card
      • Explore NFT Collections
      • My NFTs
      • Profile
        • Withdraw Earnings
        • Manage Collections
  • Guides
    • Zus GO SDK
    • Zus JS SDK
    • Zbox CLI
      • Repo
      • Get Started
      • Creating and Managing Allocations
      • Uploading and Managing Files
      • Lock and Unlock Tokens
      • Tips and Troubleshooting
    • Zwallet CLI
      • Repo
      • Get Started
      • Zwallet Operations
      • Staking on miners and sharders
      • Burn and Mint Tokens using Zwallet
      • Troubleshooting
    • Add a Blobber
      • Repo
      • Getting Started
    • Add a Miner/Sharder
      • Repo
      • Getting Started
    • Setup a Blockchain
      • Repo
      • Quickstart
        • Understand the Script
      • Step 1: Set up the project
      • Step 2: Setup the network for Züs components
      • Step 3: Initialize and Build the Züs components
      • Step 4: Start Sharder and Miner Containers
      • Step 5 : Create a wallet using zwalletcli
      • Step 6: Starting the blobber containers
      • Step 7: Validate Züs deployment
      • Step 8: Creating an Allocation on Blobber
      • Restarting Sharder and Miner Containers with CleanDB.
      • Additional Tips and Troubleshooting
    • Glossary
  • Support
    • Help Center
      • Community
      • Issues on Github
      • Contact Us
Powered by GitBook
On this page
  1. Guides
  2. Züs js-sdk
  3. js-sdk sample webapp
  4. Describing Code

Adding File Operation Functionalities

Last updated 2 years ago

File Operation Functions
  const handleUploadFiles = async (event) => {
    console.log("handleUploadFiles", event.currentTarget.files);
    setFilesForUpload(event.currentTarget.files);
  };

  const uploadClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation for upload");
      return;
    }
    if (!(filesForUpload && filesForUpload.length > 0)) {
      alert("Please select the files for upload");
      return;
    }
    console.log(
      "uploading to allocation",
      selectedAllocation.id,
      filesForUpload
    );
    if (filesForUpload && filesForUpload.length > 0) {
      const objects = [];
      const allocationId = selectedAllocation.id;
      for (const file of filesForUpload) {
        objects.push({
          allocationId: allocationId,
          remotePath: `/${file.name}`,
          file: file,
          thumbnailBytes: null,
          encrypt: false,
          isUpdate: false,
          isRepair: false,
          numBlocks: 100,
          callback: function (totalBytes, completedBytes, error) {
            console.log(
              file.name +
                " " +
                completedBytes +
                "/" +
                totalBytes +
                " err:" +
                error
            );
          },
        });
      }

      const results = await bulkUpload(objects);

      console.log("upload results", JSON.stringify(results));
    }
  };

  const downloadClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation for download");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for download");
      return;
    }
    console.log(
      "downloading from allocation",
      selectedAllocation.id,
      selectedFile.path
    );
    //allocationID, remotePath, authTicket, lookupHash string, downloadThumbnailOnly bool, numBlocks int
    const file = await download(
      selectedAllocation.id,
      selectedFile.path,
      "",
      "",
      false,
      10
    );
    console.log("downloaded file", file);

    const a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";

    a.href = file.url;
    a.download = file.fileName;
    a.click();
    window.URL.revokeObjectURL(file.url);
    document.body.removeChild(a);
  };

  const shareClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation for share");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for share");
      return;
    }
    console.log("share file", selectedAllocation.id, selectedFile.path);
    //allocationId, filePath, clientId, encryptionPublicKey string, expireAt int, revoke bool,availableAfter string
    const authTick = await share(
      selectedAllocation.id,
      selectedFile.path,
      "",
      "",
      0,
      false,
      0
    );
    console.log("authTicket", authTick);
    setAuthTicket(authTick);
  };

  const downloadSharedClick = async () => {
    if (authTicket) {
      console.log("downloading using authTicket", authTicket);

      //allocationID, remotePath, authTicket, lookupHash string, downloadThumbnailOnly bool, numBlocks int
      const file = await download("", "", authTicket, "", false, 10);
      console.log("downloaded file", file);

      const a = document.createElement("a");
      document.body.appendChild(a);
      a.style = "display: none";
      a.href = file.url;
      a.download = file.fileName;
      a.click();
      window.URL.revokeObjectURL(file.url);
      document.body.removeChild(a);
    }
  };

  const listFilesClick = async () => {
    try {
      const list = (await listObjects(selectedAllocation.id, "/")) || [];
      console.log("file list", list);
      setFilesList(list);
    } catch (error) {
      console.log("error:", error);
    }

    try {
      const destList =
        (await listObjects(selectedAllocation.id, "/test")) || [];
      console.log("dest file list", destList);
      setDestFilesList(destList);
    } catch (error) {
      console.log("error:", error);
    }
  };

  const selectFile = (file) => {
    setSelectedFile(file);
    console.log("selected file", file);
  };

  const showLogsClick = async () => {
    await showLogs();
  };

  const hideLogsClick = async () => {
    await hideLogs();
  };

  const getAppendedFileName = (filename, postfix) => {
    const isExtnExist = filename.lastIndexOf(".") > 0;
    const newFileName = isExtnExist
      ? filename.substring(0, filename.lastIndexOf(".")) +
        postfix +
        filename.substring(filename.lastIndexOf("."), filename.length)
      : filename + postfix;
    console.log("getAppendedFileName", newFileName);
    return newFileName;
  };

  const copyClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for copy");
      return;
    }
    console.log("copy file", selectedAllocation.id, selectedFile.path);
    //allocationId, path, destination
    await copyObject(selectedAllocation.id, selectedFile.path, "/test");
    console.log("copy completed");
  };

  const moveClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for move");
      return;
    }
    console.log("move file", selectedAllocation.id, selectedFile.path);
    //allocationId, path, destination
    await moveObject(selectedAllocation.id, selectedFile.path, "/test");
    console.log("move completed");
  };

  const deleteClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for delete");
      return;
    }
    console.log("delete file", selectedAllocation.id, selectedFile.path);
    //allocationId, path
    await deleteObject(selectedAllocation.id, selectedFile.path);
    console.log("delete completed");
  };

  const renameClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for rename");
      return;
    }
    console.log("rename file", selectedAllocation.id, selectedFile.path);
    //allocationId, path, newName
    await renameObject(
      selectedAllocation.id,
      selectedFile.path,
      getAppendedFileName(selectedFile.path, "_new")
    );
    console.log("rename completed");
  };

  let player;

  let isPlayerReady = false;

  const playClick = async () => {
    player = document.getElementById("player");
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for play");
      return;
    }
    console.log("playing file", selectedAllocation.id, selectedFile.path);

    if (isPlayerReady) {
      if (player.paused) {
        player.play();
      }
    } else {
      const file = selectedFile;
      console.log("playing file", file);
      const isLive = file.type == "d";

      if (file) {
        const allocationId = selectedAllocation.id;
        startPlay({
          allocationId,
          videoElement: player,
          remotePath: file?.path,
          authTicket: "",
          lookupHash: file?.lookup_hash,
          mimeType: file?.mimetype,
          isLive: isLive,
        });
        isPlayerReady = true;
      }
    }
  };

  const playSharedClick = async () => {
    player = document.getElementById("player");

    if (isPlayerReady) {
      if (player.paused) {
        player.play();
      }
    } else {
      const isLive = false;

      if (authTicket) {
        const allocationId = selectedAllocation.id;
        startPlay({
          allocationId,
          videoElement: player,
          remotePath: "",
          authTicket: authTicket,
          lookupHash: "",
          mimeType: "",
          isLive: isLive,
        });
        isPlayerReady = true;
      }
    }
  };

  const pauseClick = async () => {
    player.pause();
  };

  const stopClick = async () => {
    if (isPlayerReady) {
      stopPlay({ videoElement: player });
      isPlayerReady = false;
    }
  };

  const createDirClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    console.log("create Dir", selectedAllocation.id, dirName);
    //allocationId, path
    await createDir(selectedAllocation.id, "/" + dirName);
    console.log("create Dir completed");
  };

  const getFileStatsClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for file stats");
      return;
    }
    console.log("getting file stats", selectedAllocation.id, selectedFile.path);
    const fileStats = await getFileStats(
      selectedAllocation.id,
      selectedFile.path
    );
    console.log("file stats completed", fileStats);
  };

  const downloadBlocksClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation for download blocks");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for download blocks");
      return;
    }
    console.log(
      "downloading blocks from allocation",
      selectedAllocation.id,
      selectedFile.path
    );
    //allocationID, remotePath, authTicket, lookupHash string, numBlocks int, startBlockNumber, endBlockNumber int64, callbackFuncName string
    const output = await downloadBlocks(
      selectedAllocation.id,
      selectedFile.path,
      "",
      "",
      10,
      0,
      10
    );
    console.log("downloaded blocks", output);
  };

const getLookupHashClick = async () => {
    if (!selectedAllocation) {
      alert("Please select allocation");
      return;
    }
    if (!selectedFile) {
      alert("Please select the file for lookup hash");
      return;
    }
    console.log("lookup hash file", selectedAllocation.id, selectedFile.path);
    //allocationId, path
    const hash = await getLookupHash(selectedAllocation.id, selectedFile.path);
    console.log("lookup hash completed", hash);
  };

Line 1 to 385 defines the file operation functionalities of web app :

  • handleUploadFiles : A helper function for selecting files to upload .

  • uploadClick : Upload file on click.Calls js-sdk function.Provide allocation and files for upload as input.

  • downloadClick : Download file on click, Calls js-sdk function.

  • shareClick : Share file on click.Calls js-sdk function.

  • downloadSharedClick : Download shared file functionality.Calls js-sdk function.Download for shared file is done via authticket which is generated with shareClick function defined above.

  • listFilesClick : List files in an allocation on click. Calls js-sdk function by passing valid allocation and directory in allocation.

  • getAppendedFileName : A helper function for listing file name in theweb app.

  • copyClick : Copy file in an allocation . Calls js-sdk function by passing valid allocation name and local file path name.

  • moveClick : Move file between directories in an allocation. Calls js-sdk function by passing valid allocation and directory path in allocation.

  • deleteClick : Delete files in an allocation.Calls js-sdk function by passing valid allocation and path for file to delete.

  • renameClick : Rename file in an allocation.Calls js-sdk function.

  • playClick: A helper function for playing a selected file in an allocation.

  • playSharedClick: A helper function for playing a shared file in an allocation

  • pauseClick: A helper function for pausing the file play.

  • stopClick: A helper function for stopping the file play.

  • createDirClick : Create Directory in an allocation.Calls js-sdk function.

  • getFileStatsClick : Get File Stats on click .Calls js-sdk function.

  • downloadBlocksClick : Download files by block . Calls js-sdk function.

  • getLookupHashClick: Get Lookup Hash for a File.Calls js-sdk function.

bulkUpload
download
share
download
listObjects
listObjects
moveObject
deleteObject
renameObject
createDir
getFileStats
downloadBlocks
getLookupHash