AppGallery Connect scenario development practice - image storage and sharing

brief introduction

In the last article Scene development practice In, we use the authentication service, cloud function, SMS service and other services of AppGallery Connect (hereinafter referred to as AGC) to realize the function of user registration notification. This time, we used the three services of cloud function, cloud storage and App Linking provided by AGC to realize the functions of image storage, online editing and sharing, and the relevant codes have been synchronized to Github.

Implementation overview

1. The user selects the picture to be uploaded on the client and calls the upload interface of cloud storage Android/iOS to upload the picture to cloud storage.

2. Create a cloud function to process pictures and select the cloud storage trigger. Whenever a new picture is uploaded in the cloud storage, the cloud function will be triggered for thumbnail processing.

3, Cloud Storage Cloud call Node.js SDK download the file interface to download the picture to memory, process the image by a specific method, then call the uploading interface in cloud storage Node.js SDK to upload the processed image back to cloud storage.

4. After downloading the thumbnail on cloud storage through the Android/iOS SDK of cloud storage, the end side generates a sharing link through AppLinking to share with friends. After friends click the link, they can directly open to the specified page of the application.

Upload pictures from the end side to cloud storage

Please login AppGallery Connect official website , and operate in the console:

1. Enable Cloud storage services

2. Create a new storage instance

3. Set cloud storage security policy

4. Set cloud storage folder structure

Actions in your app:

1. Use the getStorageReference method in the Android SDK of cloud storage to create a reference for the cloud address where the uploaded file is stored:

AGCStorageManagement storageManagement = AGCStorageManagement.getInstance();
StorageReference reference = storageManagement.getStorageReference("images/demo.jpg");

2. Call the upload interface in the SDK to upload local files to the storage instance: ··· uploadtask task = reference.putfile (new file ("path / images / test. JPG"); task.addOnFailureListener(new OnFailureListener(){ @Override public void onFailure(@NonNull Exception exception) { } }).addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>(){ @Override public void onSuccess(UploadTask.UploadResult uploadResult) { } }); ···

Cloud function processing picture size

Actions in your app:

1. Call the cloud storage Node.js SDK, specify the instance and bucket to be downloaded, and specify the local address:

const storage = new StorageManagement();
const bucket = storage.bucket("photo-7iawi");
const remoteFile = bucket.file(fileAddr);
localAddr = "\ImageProcess\picture";

2. Call method Download File:

try {
        remoteFile.createReadStream()
        .on('error', err => {
          result = {"message":"download file error, " + err.message};
          callback(result);
        })
        .on('end', () => {
            result = {"message":"download file success"};
            // callback(result);
        })
        .pipe(fs.createWriteStream(localFile));
    } catch (error) {
        result = {"message":"download file error, " + error.message};
        callback(result);
    }

3. After downloading the file, process the image resolution.

4. After the image processing is completed, upload the new image back to cloud storage.

const options = {
        destination: 'thumbnail/' + fileName,
        onUploadProgress: (event) => {
        }
    };

    bucket.upload(imageAddr, options)
        .then(res => {
            result = {"message":"All Success"};
            callback(result);
        }).catch(err => {
            result = {"message":"upload failed"};
            callback(result);
        });

Cloud storage triggers cloud functions

Actions in the AppGallery Connect console:

1. Login AppGallery Connect , locate the cloud function and enable it.

2. Create a new function and set the function name, deployment information and other related settings.

3. At the "code file" configuration item, upload the function deployment package for processing image size to the cloud function.

4. Create a cloud storage trigger, enter the name of the previously created storage instance and select the event name as Complete (meaning that the cloud function will be triggered to trim the image after the image is uploaded successfully).

App Linking link sharing

Please login AppGallery Connect official website , and operate in the console:

1,Enable App Linking service.

2. After the service is enabled, create a unique link prefix in the whole network in the link prefix tab.

3. Configure the SHA256 file of your application signature. For specific configuration methods, please refer to Configure signing thumbprint certificate.

Actions in your app:

1. Use the cloud storage interface to obtain the download link of the corresponding image.

private String downloadUrl;
private void getDownLoadUrl() {
    AGCStorageManagement storageManagement = AGCStorageManagement.getInstance();
        StorageReference reference = storageManagement.getStorageReference("images/demo.jpg");
        Task<Uri> task = reference.getDownloadUrl();
        task.addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) { 
                String downloadUrl = uri.toString();
            }
        });
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
            }
        });
    }

2. Generate a sharing link with the download link and the corresponding picture ID.

private String shortLink;
private static final String DOMAIN_URI_PREFIX = "https:// DomainUriPrefix.drcn.agconnect.link";
    private static final String SHARE_DEEP_LINK = "share://photo.share.com";
    private void createShareLinking(String UserName, String PhotoID, String ImageUrl) {
        String newDeep_Link = SHARE_DEEP_LINK  + "?PhotoID=" + PhotoID;
        AppLinking.Builder builder = AppLinking.newBuilder()
                .setUriPrefix(DOMAIN_URI_PREFIX)
                .setDeepLink(Uri.parse(ImageUrl))
                .setAndroidLinkInfo(AppLinking.AndroidLinkInfo.newBuilder()
                        .setAndroidDeepLink(newDeep_Link)
                        .build())
                .setSocialCardInfo(AppLinking.SocialCardInfo.newBuilder()
                        .setTitle("It is a beautiful Photo")
                        .setImageUrl(ImageUrl)
                        .setDescription(UserName + " share a Photo to you")
                        .build())
                .setCampaignInfo(AppLinking.CampaignInfo.newBuilder()
                        .setName("UserSharePhoto")
                        .setSource("ShareInApp")
                        .setMedium("MediumExample")
                        .build());
        builder.buildShortAppLinking().addOnSuccessListener(shortAppLinking -> {
            shortLink = shortAppLinking.getShortUrl().toString();
        }).addOnFailureListener(e -> {
        });
    }
        ```

3,stay AndroidManifest Medium configuration Intent-Filter,For receiving App Linking Link and directly pull up the application
```

4. In the OnCreate method of the application startup page, the method that receives and processes the App Linking link.

AGConnectAppLinking.getInstance().getAppLinking(LoginActivity.this).addOnSuccessListener(resolvedLinkData -> {
    Log.i(TAG,"StartUp From AppLinking");
    if (resolvedLinkData!= null) {
        String deepLink = resolvedLinkData.getDeepLink().toString();
        // your action of StartUp From AppLinking 
    }
}).addOnFailureListener(e-> {
    Log.i(TAG,"Normal StartUp");
    // your action of Normal StartUp 
});

Test function

You can do the following to test whether pictures or videos can be shared normally:

1. Open your app, take a random picture and store it in your phone.

2. View the processing effect after image upload.

3. Enter the picture details interface, click the sharing link in the upper right corner to check whether a link is generated and sent to friends.

4. Log in to the application with your friend account, check and click the link to test whether the shared picture page can be opened normally.

For more information, please Download Demo.

Reference documents:

Upload pictures using cloud storage:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-cloudstorage-upload-android-0000001055326211

Using Applinking to share links:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-applinking-createlinks-bysdk-android-0000001055674692

Create cloud function:

https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-cloudfunction-config-0000001058511532

For more highlights, please see the official Huawei Developer Forum → https://developer.huawei.com/consumer/cn/forum/home?ha_source=sanfang

Keywords: huawei

Added by Fakcon on Fri, 19 Nov 2021 11:33:37 +0200