AppGallery Connect Cloud Storage is scalable and maintenance-free. When the Cloud Storage SDK is integrated, it provides you with the functions such as storage instance management, file management, and file metadata management.
In this codelab, you will create a server-side app that integrates Cloud Storage capabilities. Your app will allow users to upload a file to the cloud and download it to a local path by calling APIs.
To integrate Cloud Storage of AppGallery Connect, you must complete the following preparations:
Before integrating the Cloud Storage SDK, you need to enable Cloud Storage in AppGallery Connect.
If you are using Java development environment, you need to integrate the Cloud Storage SDK into your Java SDK project before development.
The Cloud Storage Java Server SDK is released in the Maven repository. You need to add the Maven repository address and Cloud Storage SDK dependency to the pom.xml file.
<repositories>
<repository>
<id>sz-maven-public</id>
<name>sz-maven-public</name>
<url>https://developer.huawei.com/repo/</url>
</repository>
</repositories>
<dependency>
<groupId>com.huawei.agconnect.server</groupId>
<artifactId>agconnect-storage</artifactId>
<version>1.2.0.300</version>
</dependency>
public static String BUCKET_NAME = "your bucket name";
CredentialService credential = CredentialParser.toCredential(path + "agc-apiclient-xxxxx-xxxxx.json");
AGCParameter agcParameter = AGCParameter.builder().setCredential(credential).build();
// Initialize a client whose name is clientName and the region code is CN. Use clientName to obtain
AGCClient.initialize("agcClient", agcParameter, "CN");
You can call related APIs of the Cloud Storage SDK to develop functions.
Before using Cloud Storage APIs, you need to initialize the cloud storage instance and file instance as required. To obtain the storage instance name, sign in to AppGallery Connect, go to Build > Cloud Storage, and check the value of Storage instance.
// Initialize multiple storage locations. For details, please refer to the AGCClient API reference.
StorageManagement storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
Call the StorageReference.putObject method to upload the file to the cloud.
private static final String OBJECT_NAME = "2M.txt";
public static void uploadFile() throws AGCException {
**2M.txt**// 2M.txt is the file to be uploa**path** and path indicates the local path to this file.
File file = new File(path+ "/2M.txt");
storageManagement =
AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
StorageReference storageReference = storageManagement.getStorageReference();
String[] result = {""};
ProgressListener listener = new ProgressListener() {
@Override
public void inProgress(ProgressStatus status) {
result[0] = "upload transferred/total:" + status.getTransferredBytes() + "/" + status.getTotalBytes()
+ "," + status.getTransferPercentage() + "%, " + "instantaneous speed: "
+ status.getInstantaneousSpeed() + ", avg speed: " + status.getAverageSpeed();
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(() -> System.out.println(result[0]), 2, 3, TimeUnit.SECONDS);
PutObjectRequest putObjectRequest = new PutObjectRequest();
putObjectRequest.setObjectMetadata(null);
putObjectRequest.setObjectName(OBJECT_NAME);
putObjectRequest.setUploadFile(file);
putObjectRequest.setProgressListener(listener);
storageReference.putObject(putObjectRequest);
System.out.println(OBJECT_NAME + " upload succeeded " + storageReference.doesObjectExist(OBJECT_NAME));
}
Call the download() method to download files from the cloud to a local device. If no storage path is specified, the file will be saved to the local project directory by default.
public static void downloadFile() throws StorageException {
StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME);
final String[] result = {""};
DownloadFileRequest request = new DownloadFileRequest();
request.setOffset(0);
request.setSaveFile(new File(OBJECT_NAME));
request.setProgressListener(new ProgressListener() {
@Override
public void inProgress(ProgressStatus status) {
result[0] = "download transferred/total:" + status.getTransferredBytes() + "/" + status.getTotalBytes()
+ "," + status.getTransferPercentage() + "%, " + "instantaneous speed: "
+ status.getInstantaneousSpeed() + ", avg speed: " + status.getAverageSpeed();
}
});
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(() -> System.out.println(result[0]), 2, 3, TimeUnit.SECONDS);
storageReference.download(request);
}
public static void getMetadata() throws StorageException {
storageManagement =
AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME);
ObjectMetadata objectMetadata = storageReference.getObjectMetadata();
System.out.println(objectMetadata.getContentType());
System.out.println(objectMetadata.getCacheControl());
System.out.println(objectMetadata.getContentEncoding());
System.out.println(objectMetadata.getContentDisposition());
System.out.println(objectMetadata.getContentLanguage());
}
public static void updateMetadata() throws StorageException {
storageManagement =
AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME);
ObjectMetadata updatedObjectMetadata = storageReference.updateObjectMetadata(initObjectMetadata());
System.out.println(updatedObjectMetadata.getContentType());
System.out.println(updatedObjectMetadata.getCacheControl());
System.out.println(updatedObjectMetadata.getContentEncoding());
System.out.println(updatedObjectMetadata.getContentDisposition());
System.out.println(updatedObjectMetadata.getContentLanguage());
}
Call the getFileList() method to obtain the file list from the cloud.
public static void listObjects() throws StorageException {
storageManagement =
AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
listObjectsRequest.setMarker("");
listObjectsRequest.setMaxKeys(100);
listObjectsRequest.setDelimiter("/");
listObjectsRequest.setListTimeout(5);
ListObjectsResult objectsResult = storageReference.listObjects(listObjectsRequest);
for (String file : objectsResult.getFileList()) {
System.out.println("file - " + file);
}
for (String dir : objectsResult.getDirList()) {
System.out.println("dir - " + dir);
}
}
Call the deleteObject() method to delete the uploaded file from the cloud.
public static void deleteFile() throws StorageException {
storageManagement =
AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);
StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME);
DeleteObjectResult deleteObjectResult = storageReference.deleteObject(OBJECT_NAME);
System.out.println("Delete object " + deleteObjectResult.getObjectName() + " succeeded");
}
Call methods to test functions. Sample code in this section is for your reference.
uploadFile();
When the message "2M.txt upload succeeded true" is displayed on the console, the file is successfully uploaded.
You can also view the upload progress on the console.
download();
When the message "download finished" is displayed on the console, the file is successfully downloaded. After the download is complete, you can find the downloaded file in the project directory.
You can also view the download progress on the console.
getFileMetadata();
After the metadata is successfully obtained, you can view the result on the console.
updateFileMetadata();
After the metadata is successfully updated, you can view the result on the console.
getFileList();
After the file list is obtained successfully, you can view the file list on the console.
deleteFile();
After this method is called, you can access the Cloud Storage page in AppGallery Connect to check whether files are successfully deleted.
Cloud Storage provides visualized file management and data analysis.
Well done. You have successfully built an app that integrates Cloud Storage of AppGallery Connect and learned how to manage Cloud Storage in AppGallery Connect.