Hi fellow developers! Today, let's talk about the practical usage of HarmonyOS Cloud Storage. I'll walk you through implementing core features like file uploading, downloading, and metadata operations. Forget the formal tone of official documentation; we'll figure out how to use these APIs in the most down-to-earth way! (Full code examples are at the end)
I. Cloud Storage Feature Overview
HarmonyOS Cloud Storage is like a portable USB drive, helping us securely store application data in the cloud. It's especially suitable for handling scenarios like user avatars, game saves, and audio/video files. It has three main advantages:
- Automatic Sync: Real-time data synchronization between the device and the cloud
- Controllable Permissions: Fine-grained access control for each file
- Massive Storage: Supports up to 1GB for a single file upload
II. Four Steps to File Upload
Preparation: Make sure the user has logged in through an authentication service (logging in with a HUAWEI ID is recommended)
// 1. Get the local file path (sandbox path example)
let localPath = "internal://app/files/photo.jpg";
// 2. Create a Storage instance
const storage = new Storage();
// 3. Execute the upload (with progress callback)
try {
const uploadResult = await storage.upload({
localPath: localPath,
cloudPath: "user_uploads/2023/photo.jpg",
onUploadProgress: (progress) => {
console.log(`Uploaded ${progress.loaded} / Total ${progress.total}`);
}
});
// 4. Process the result
console.log(`Upload successful! Bytes transferred: ${uploadResult.bytesTransferred}`);
} catch (error) {
console.error("Upload failed:", error);
}
Tips:
- File paths must start with
<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">internal://app/</font>
for the sandbox path. - If you encounter permission issues, remember to add permissions like
<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">ohos.permission.READ_MEDIA</font>
in<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">config.json</font>
. - Large file uploads will automatically resume from breakpoints (retries up to 5 times).
III. File Download in Action
Want to save a cloud file to your local device? Try this:
// Download to the 'downloads' directory in the sandbox
let savePath = "internal://app/downloads/demo.jpg";
const downloadResult = await storage.download({
cloudPath: "user_uploads/2023/photo.jpg",
localPath: savePath,
onDownloadProgress: (progress) => {
console.log(`Download progress: ${(progress.loaded/progress.total*100).toFixed(1)}%`);
}
});
console.log(`File saved to: ${savePath}`);
Important Reminders:
- The download path must be within the application sandbox.
- You can verify file integrity using
<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">getFileHash()</font>
. - Check for sufficient local storage space before use.
IV. Advanced File Metadata Usage
Cloud Storage supports adding "identity information" to files:
Set Metadata (e.g., setting a cache policy):
await storage.setMetaData({
cloudPath: "user_uploads/2023/photo.jpg",
metaData: {
contentType: "image/webp",
cacheControl: "max-age=3600",
customMetadata: {
author: "Developer Xiaoming",
version: "2.0"
}
}
});
Get Metadata:
const fileInfo = await storage.getMetaData("user_uploads/2023/photo.jpg");
console.log(`File type: ${fileInfo.contentType}`);
console.log(`Custom field: ${fileInfo.customMetadata.author}`);
V. File Deletion Operation
Unneeded files should be cleaned up promptly:
try {
await storage.deleteFile("user_uploads/2023/obsolete.jpg");
console.log("File deleted");
} catch (error) {
console.log("Deletion failed, file may not exist");
}
VI. Advanced Tips & Tricks
- Visual Operations in the Console: Directly drag and drop to upload/download files in the AppGallery Connect console, suitable for operations personnel.
- Security Rule Configuration:
// Example: Allow users to operate only on their own files
"match /users/{userId}/{file}": {
allow read, write: if request.auth.uid == userId;
}
-
Best Practices:
- Enable version control for important files.
- Periodically clean up temporary files.
- Combine with Cloud Functions for automatic file processing (like thumbnail generation).
Conclusion
Using Cloud Storage is actually pretty simple, right? I hope this guide helps you avoid some detours. If you run into issues during development, feel free to post on the Huawei Developer Forum for discussion (remember to add the #HarmonyOSCloudStorage tag), or you can @ me directly to chat!
Wishing you all smooth development, see you next time!🚀
Top comments (0)