DEV Community

陈杨
陈杨

Posted on

HarmonyOS5 Cloud Service Technology Sharing--ArkTS Calling Function

✨【HarmonyOS Practical Guide】A Step-by-Step Guide to Mastering Cloud Function File Retrieval with ArkTS✨

Hello everyone! Today let's talk about how to implement the cloud function file retrieval feature using HarmonyOS's ArkTS language. The whole process is as fun as building blocks, and we guarantee that even beginners can get started easily! (There's a complete code template at the end of the article!)

🔧 Prerequisites

1️⃣ Log in to the Huawei AppGallery Connect console

2️⃣ Make sure you have created a Cloud Functions project (if not, go and create one in the console)

🚀 Four Core Steps:

🌈 Step 1: Create an HTTP Trigger

Go to the function details page -> Click the "Triggers" tab -> Add a new trigger

When configuring the parameters, pay attention to the following:

  • Trigger Type: Select HTTP
  • Request Method: Currently only POST is supported
  • Authentication Type: Choose based on your scenario: ▫️ API Client Authentication (for Client): For APP/local application calls ▫️ API Client Authentication (for Server): For calls between cloud functions
  • Check the decode option (essential for handling form data)

💡 Tip: After saving the configuration, remember to click the "Save" button in the upper right corner!

🔍 Step 2: Obtain Key Information

After successfully creating the trigger:

  1. Copy the suffix from the trigger URL (format: functionName-version) For example: myhandler1234-$latest
  2. Function Name: myhandler1234
  3. Version: $latest

📝 Step 3: Write the Calling Code

Basic call example:

let functionResult = await cloud.callFunction({
  name: "your_function_name", 
  params: {
    "fileId": "123456",
    "action": "download"
  }
});
Enter fullscreen mode Exit fullscreen mode

Advanced configuration version:

let functionResult = await cloud.callFunction({
  name: "myhandler1234",
  version: "v2.0",  // Defaults to the latest version if not specified
  timeout: 15000,   // Set timeout to 15 seconds
  params: {
    "fileType": "pdf",
    "isPreview": true
  }
});
Enter fullscreen mode Exit fullscreen mode

📦 Step 4: Process the Returned Data

// Get the binary file stream
let fileData = functionResult.getValue();

// If the file is base64 encoded
let decodedFile = base64.decode(fileData);
Enter fullscreen mode Exit fullscreen mode

⚠️ Troubleshooting Guide:

  1. It is recommended to pass file parameters as a JSON object
  2. Remember to adjust the timeout for large file transfers (default is 70 seconds)
  3. Don't forget to add a try-catch block for error handling
  4. Ensure proper security authentication is in place for the production environment

🎯 Practical Tips:

  • Specify the file type using the contentType parameter
  • Use chunked transfer to optimize large file downloads
  • Implement file persistence by integrating with a cloud storage service

Complete File Retrieval Template:

async function fetchCloudFile(fileId: string) {
  try {
    const result = await cloud.callFunction({
      name: "fileHandler",
      params: {
        operation: "getFile",
        fileId: fileId
      },
      timeout: 30000
    });

    const fileBuffer = result.getValue();
    // Add your file processing logic here
    console.log("File retrieved successfully!");
    return fileBuffer;
  } catch (error) {
    console.error("An error occurred:", error);
    return null;
  }
}
Enter fullscreen mode Exit fullscreen mode

🌟 Summary:

By combining Cloud Functions with HTTP triggers, we have implemented a secure and efficient file retrieval solution. This approach not only ensures business logic flexibility but also leverages the stability and reliability of Huawei Cloud services. It is recommended to adjust the timeout and authentication policies according to your actual needs.

Don't worry if you encounter problems! Feel free to leave a message in the comments section for discussion, or ask questions in the Huawei Developer Community (remember to add the #HarmonyOSCloudFunctions tag). More practical tips will be shared later, so follow me to stay updated!💪

Top comments (0)