HarmonyOS + OBS Cloud Album: Signed Uploads and Smart Previews
Photos and videos are the files we least want to lose, and the ones we most often leave scattered across phones, chat apps, and old laptops. A personal cloud album solves the scattering problem, but only if the upload path is trustworthy: the app must prove who it is to the storage service, never leak credentials, and never silently lose a file. This article walks through building such an album on HarmonyOS with Huawei Cloud OBS (Object Storage Service), based on the HarmonyOS practice case “Building a Personal Cloud Album App with OBS”. It covers the four pieces that actually decide whether the app works in daily use: bucket setup, Header signing, reliable per-file upload, and fast cloud preview.
What the app does
The app reads photos and videos from the device album, backs them up file by file to a private OBS bucket, keeps a local backup record for each file, and lets the user browse the cloud copy in a list or grid, open an object detail page, and preview images and videos. It targets HarmonyOS API 26 and is written in ArkTS with ArkUI. The learning goal is not the gallery UI, which is straightforward, but the cloud round trip: sign a request, upload one file, confirm it landed, and fetch it back through a signed read.
A useful mental model is four layers. ArkUI pages own the gallery, backup records, cloud list, and settings screens. A media scanner reads the system album through the photo access helper. A backup service decides what still needs uploading, tracks progress, and handles cancellation. An OBS client builds signed HTTPS requests and nothing else. Configuration and backup records live in the app sandbox preferences. Keeping the OBS client separate matters: every request goes through one signing path, so a bug in authentication shows up in one place instead of five.
1. Prepare OBS first, code second
Create the bucket before writing upload code. In the OBS console, open Bucket List, create a bucket with standard storage and private access, and pick the region you will actually use. The bucket name must be globally unique, lowercase letters, digits, and hyphens, for example album-demo-7m3x9, and it cannot be renamed later, so choose deliberately. If you buy a storage resource pack, its region and single-AZ or multi-AZ redundancy must match the bucket; a mismatch means the pack will not offset the usage and you will be billed on demand. Buying a pack does not create a bucket, and a bucket is not created automatically by any other step.
The app needs four configuration values: the Access Key (AK), the Secret Access Key (SK), the region Endpoint, and the bucket name. Get the bucket name and Endpoint from the bucket overview page. The Endpoint is a regional domain such as obs.cn-north-4.myhuaweicloud.com; it contains no bucket name, object path, or port, and the example is only for the Beijing 4 region, so copy the value for your own region instead of copying the example. Get the AK and SK from My Credentials, Access Keys. The SK is shown only when the key is created, so download and store the key file safely at that moment; a lost SK means creating a new key and replacing it.
Do not use the account owner key in the app. Create a dedicated IAM user with programming access, and grant it only what this app needs on this one bucket: obs:bucket:ListBucket on the bucket, and obs:object:PutObject and obs:object:GetObject on objects inside it. That is the least-privilege shape: if the key ever leaks, the damage is limited to one test bucket. Treat the AK and SK as secrets everywhere: type them only into the app settings screen, never paste them into chat, code, logs, screenshots, or a public issue. The settings screen masks the input, but masking is only display hiding; the values still sit in the app sandbox, so a production app should move to a proper temporary-authorization scheme rather than storing long-lived keys on the device.
2. Header signing: prove the request is yours
OBS Header authentication is the heart of the app, and it is also the step where most first attempts fail. Every request carries an Authorization header of the form OBS AK:Signature. The signature is an HMAC-SHA1 digest, computed with the SK, over a canonical string built from the request method, content headers, normalized x-obs- headers, and the canonicalized resource (bucket and object path). The result is Base64 encoded. The server recomputes the same digest; if anything differs, the request is rejected with SignatureDoesNotMatch.
That exactness is the point. A single difference in the resource path, an extra header included in the signature on one side and not the other, or a wrong content type will change the digest. When signing fails, do not guess: log the canonical string your client built, compare it field by field with the OBS documentation, and check the four configuration values first, because a wrong Endpoint or bucket name changes the resource and therefore the signature. Also check the device clock; a large time skew can break time-sensitive authentication.
In ArkTS, the signing step is a small, testable function. The following sketch shows the shape, using the crypto framework for HMAC-SHA1. It is simplified for illustration; check the current SDK signatures before compiling:
// Simplified illustration: build the Authorization header for an OBS request.
async function signObsRequest(method: string, resource: string,
ak: string, sk: string): Promise<string> {
const canonical = `${method}\n\n\n${resource}`; // add content headers and x-obs headers here
const hmac = cryptoFramework.createHmac('SHA1');
const key = await hmac.initKey(sk);
await hmac.update({ data: stringToUint8(canonical) });
const digest = await hmac.doFinal();
return `OBS ${ak}:${base64Encode(digest.data)}`;
}
Keep this function pure: same inputs, same output, no network, no UI. Then you can unit-test it against a known vector before ever touching a real bucket. A second rule follows from the same idea: build the canonical string in exactly one place. If the upload path and the download path each assemble their own string, they will drift apart, and one of them will start failing after an unrelated edit.
3. Read the album, then upload one file at a time
Reading the local album goes through the system photo access helper, not through raw file paths. Request photo and video read permission first, and handle the case where the user grants only partial access or denies it: the gallery should explain what is missing instead of showing a blank page. The scanner returns photo and video assets with metadata, and the app should page through them rather than loading the whole library into memory at once.
Upload is deliberately per file, not one big batch. For each selected asset the app computes an MD5 of the content, chooses a target object name that isolates the file from other files, and issues a signed PUT. Target isolation matters because two different photos can share a file name; the object key must distinguish them, for example by combining a stable asset identifier with the content hash. The backup record stores the asset, the target object, and the MD5, so a later run can recognize a file that is already backed up instead of uploading it again.
Two details prevent data loss. First, send the x-obs-forbid-overwrite header so a second upload cannot silently overwrite an existing object with the same key; in a versioned bucket, remember that this does not stop a new version from being created, so check the bucket configuration and the documentation for your case. Second, show real progress and support cancellation, and treat a cancelled upload as unfinished rather than as backed up. The record should only flip to backed up after the server confirms the object is readable, which the app can verify by listing it or fetching its metadata.
There is a hard size boundary: a single-file upload and a single preview are capped at 64 MiB in this case. That covers ordinary photos and short clips, but a family video over 64 MiB needs multipart upload, which splits the file into parts, uploads them, and merges them into one object. Do not work around the limit by raising a memory buffer or by treating a part ETag as the whole-file MD5; a multipart ETag is not the file MD5, and confusing the two breaks the deduplication check. Design the large-file path as its own feature, with its own tests for failure, cancellation, and merging.
4. Cloud listing and preview: make the cloud copy feel local
A backup nobody can browse is a backup nobody trusts. The cloud list is a signed ListObjects call, and the object detail page shows the key, size, and last-modified time returned by OBS. Note that this time is the upload or backup time, not the photo’s shooting time, so do not label it as the capture date. Photos and videos are fetched with a signed GET, and the app caches previews on disk so scrolling back does not re-download everything. Keep the cache bounded: in this case the preview disk cache is capped at 128 MiB with at most 64 thumbnails. When the cache is full, evict the oldest entries instead of growing without limit, and never treat the preview cache as the backup itself; it is a convenience copy, and the object in OBS is the real one.
5. Troubleshooting the failures you will actually meet
- SignatureDoesNotMatch (403): recheck the Endpoint, bucket name, AK/SK, device time, and the canonical string, then look at the actual server response before changing code.
- Empty gallery: confirm the device has test media and that photo and video read permission was granted.
- Preview fails: check object read permission, network, file size, and format. Remember that reading the original object costs requests and traffic.
- A file backs up twice: check the backup record and MD5 for the same target; clearing app data also clears the local record, so the app will see the file as new.
6. Security and cleanup
Use minimum-permission credentials and non-sensitive test media. Rotate or revoke a test key when it is no longer needed, save the project and data you want to keep, then stop cloud workspaces and devices you no longer use, delete test objects and buckets you no longer need, and confirm the charges. If the bucket has versioning enabled, deleting the current object does not necessarily delete earlier versions, so clean up by the console’s actual version list.
Checklist before you call it done
Bucket is private and in the right region; the IAM key has only the three permissions listed above; a test photo backs up and appears in the cloud list; the same file is not uploaded twice; a signed preview opens; and a failed or cancelled upload leaves a clear, visible state. When all six are true, you have more than a demo: you have a small, honest cloud album, and the same signing, dedup, and caching patterns transfer directly to any other object-storage-backed HarmonyOS app.
- 点赞
- 收藏
- 关注作者
评论(0)