Contents
- Preface
- Feature Overview 
- 
Core Code - Imported Kits
 
- UI Button for Download 
- 
Function for Saving Online Images to the Gallery - Function Explanation
 
- Notes 
Preface
Hello everyone, I am Ruocheng. This series aims to help developers quickly implement small features during HarmonyOS app development. Note that this series will not provide extensive explanations or complex demonstrations, but developers can directly copy and paste the code to implement the feature. However, permissions that need to be requested should be handled by the developers themselves, as this series will not cover very basic concepts.
Feature Overview
This article explains how to implement a feature in HarmonyOS apps that allows users to download images from the Internet and save them to the device's gallery. This is a common requirement for scenarios such as image browsing or social media apps, where users often want to save their favorite pictures locally.
Core Code
Imported Kits
import { abilityAccessCtrl, common } from '@kit.AbilityKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';
import { http } from '@kit.NetworkKit';
import { promptAction } from '@kit.ArkUI';
private appContext: common.Context = getContext(this);
private atManager = abilityAccessCtrl.createAtManager();
@State downLoadImg:boolean = false;
The role of these modules:
- 
AbilityKit:Handles permission management
- 
MediaLibraryKit: Accesses and manages the gallery
- 
fs:Performs file system operations
- 
NetworkKit:Handles network requests
- 
ArkUI:Provides UI interaction components
UI Button for Download
                    // Download button
                    Column() {
                        Image($r("app.media.downImg"))
                            .width(24)
                            .height(24)
                        Text('Download')
                            .fontSize(12)
                            .fontColor('#FFFFFF')
                            .margin({ top: 4 })
                    }
                    .onClick(() => {
                        if (this.downLoadImg){
                            promptAction.showToast({
                                message: 'Downloading, please wait',
                                duration: 1000,
                            });
                        }else{
                            this.saveFile(this.dataList.pic_url)
                        }
                    })
                    .margin({ right: 32 })
Feature Explanation
When the button is clicked, the program checks whether this.downLoadImg is true. If it is true, it means the download process has already been triggered and there is no need to start another one. Otherwise, it calls the this.saveFile function and passes the image‘s network URL as a parameter.
Function for Saving Online Images to the Gallery
// Save image to the gallery
    async saveFile(url: string) {
        this.downLoadImg = true;
        // Request permission and save the image to the gallery
        try {
            // Request the permission for the gallery management module: 'ohos.permission.WRITE_IMAGEVIDEO'
            this.atManager.requestPermissionsFromUser(this.appContext, ['ohos.permission.WRITE_IMAGEVIDEO'])
                .then(async () => {
                    //Permission granted, proceed to save the image
                    let context = getContext();
                    // Get an instance of the gallery management module for accessing and modifying media files in the album
                    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
                    // After the onClick is triggered, the createAsset API can be used within 10 seconds to create an image file. The temporary authorization will expire after 10 seconds.
                    promptAction.showDialog({
                        title: "Downloading image... .",
                    })
                    let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
                    // Create a media file
                    let file = fs.openSync(uri, fs.OpenMode.READ_WRITE || fs.OpenMode.CREATE);
                    let totalSize = 0;
                    let httpRequest = http.createHttp();
                    httpRequest.on("dataReceive", (data: ArrayBuffer) => {
                        let writeLen = fs.writeSync(file.fd, data);
                        totalSize = totalSize + writeLen;
                    });
                    httpRequest.requestInStream(url,
                        { method: http.RequestMethod.GET, connectTimeout: 3000, }, httpCode => {
                            console.info('requestInStream HTTP CODE is', httpCode)
                        })
                    httpRequest.on("dataEnd", () => {
                        fs.close(file);
                        promptAction.showDialog({
                            title: "Image download completed and saved to gallery",
                            message: `Image size: ${totalSize} bytes`
                        })
                        this.downLoadImg = false;
                    })
                })
        } catch (err) {
            console.error(`requestPermissionsFromUser call Failed! error: ${err.code}`);
            this.downLoadImg = false;
        }
    }
Function Explanation
- 
Permission request:
- Uses atManager.requestPermissionsFromUser to request the WRITE_IMAGEVIDEO permission, which is required for saving images to the gallery.
 
- 
Media resource creation:
- Get the gallery access helper instance via photoAccessHelper.getPhotoAccessHelper(context).
- Create image resources using phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'), specifying the type as image and the format as JPG.
 
- File operations::
- Open the file in read/write mode with fs.openSync, creating it if it does not exist.
- Write received data to the file with fs.writeSync.
 
- 
Network request::
- Create an HTTP request via http.createHttp().
- Set the data reception event listener: httpRequest.on("dataReceive", …).
- Use httpRequest.requestInStream to perform a streaming download, which is suitable for large files.
- Set the request completion event listener: httpRequest.on("dataEnd", …).
 
- 
User interaction:
- Display a dialog when the download starts: promptAction.showDialog({ title: "Downloading image..." }). ." })
- Display a completion message when the download finishes: promptAction.showDialog({ title: "Image download completed and saved to the gallery", message: ... }). })
- Use the state variable downLoadImg to prevent repeated downloads.
 
Notes
These three code segments form a complete functional unit. Developers are advised to review them as a whole to fully understand the logic and purpose of each variable. Alright, class dismissed
 


 
    
Top comments (0)