Remote Communication Kit can work with Core File Kit to quickly upload and download files, directories, and objects. In the process, Remote Communication Kit provides APIs for remote connection and data transmission, and Core File Kit offers APIs for efficiently performing operations such as reading and writing files. They work together to implement quick upload and download.
The quick upload/download capability supports phones, 2-in-1 devices, tablets, and wearables. Starting from version 5.1.1(19), it is also supported on TVs.
Import required modules. In this example, besides the modules for request initiation and response processing, the fileIo module of CoreFileKit is also required.
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit'; Define the download path and create related configurations. To also access app files, please refer to Application Files.
// Path for storing the downloaded file. This is only an example. Change it to the actual path.
const DOWNLOAD_TO_PATH = `/data/storage/el2/base/entry/temp/DownloadFilePath`;
// Create a security configuration object, in which, set remoteValidation to 'skip', indicating that remote verification will be skipped.
const securityConfig: rcp.SecurityConfiguration = {
remoteValidation: 'skip'
}
// Create a download configuration object, in which, set kind to 'folder', indicating that the download target is a folder, and set path to the previously defined DOWNLOAD_TO_PATH.
let downloadToFile: rcp.DownloadToFile = {
kind: 'folder',
path: DOWNLOAD_TO_PATH
}
// ...
// Create an HTTP session and customize request configurations including the transmission timeout configuration and security configuration.
const session = rcp.createSession({
requestConfiguration: {
transfer: { timeout: { connectMs: 6000, transferMs: 6000, inactivityMs: 6000 } },
security: securityConfig
}
}) Check whether the target path exists. If so, delete the path to ensure that the downloaded file does not overwrite the existing file. Then, initiate a request and use the created session to download the content at the URL https://example.com/test.png to the specified local path. If the download is successful, display a success message; otherwise, display an error message.
// Check whether the target path exists.
if (fileIo.accessSync(DOWNLOAD_TO_PATH)) {
fileIo.rmdirSync(DOWNLOAD_TO_PATH);
}
// Initiate a request to download the target. Here, 'https://example.com/test.png' is a sample image URL.
session.downloadToFile('https://example.com/test.png', downloadToFile)
.then((response: rcp.Response) => {
console.info(`Successfully received the response, statusCode: ${JSON.stringify(response.statusCode)}`);
// ...
}).catch((err: BusinessError) => {
console.error(`Failed, the error code is ${err.code}, error data is ${err.data}`)
// ...
}) Import required modules. In this example, besides the modules for request initiation and response processing, the fileIo module of CoreFileKit is also required.
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit'; Define an object named SESSION_CONFIG to configure the request session. The configuration covers transmission timeout and security settings (such as remote authentication and TLS version).
let SESSION_CONFIG: rcp.SessionConfiguration = {
requestConfiguration: {
transfer: {
timeout: {
connectMs: 6000
}
},
security: {
remoteValidation: 'skip',
tlsOptions: {
tlsVersion: 'TlsV1.2'
}
}
}
} Define the FdReadFile class to read the file to which the file descriptor points. The read method asynchronously reads the specified ArrayBuffer and returns the number of bytes that are actually read.
class FdReadFile {
public readonly fd: number;
constructor(fd: number) {
this.fd = fd;
}
async read(buffer: ArrayBuffer): Promise<number> {
return fileIo.read(this.fd, buffer);
}
} Create a session and open a file in read-only mode. The fileIo.openSync method returns a file descriptor. If the file fails to be opened, error information will be returned.
const session = rcp.createSession(SESSION_CONFIG);
const file = fileIo.openSync('/data/storage/el1/bundle/entry/resources/resfile/upload_file.txt',
fileIo.OpenMode.READ_ONLY);
if (file === undefined) {
console.error('fileIo.openSync failed');
return;
} Create an FdReadFile instance, and allocate a buffer to read the file. The read method is executed asynchronously. You need to wait for the reading to finish.
const fdReadFile = new FdReadFile(file.fd); const buffer = new ArrayBuffer(1024 * 1024); // Assume that the file size is 1 MB. await fdReadFile.read(buffer);
Use the uploadFromFile method of the session to upload a file to the specified URL. The UploadFromFile function accepts a file descriptor. When the upload either succeeds or fails, the corresponding information will be displayed.
// Initiate a request to upload the target. Here, 'https://httpbin.org/anything' is a sample URL.
session.uploadFromFile('https://httpbin.org/anything', new rcp.UploadFromFile(fdReadFile))
.then((response: rcp.Response) => {
console.info(`Upload succeeded: ${response}`)
// ...
})
.catch((err: BusinessError) => {
console.error(`Upload failed: error code is ${err.code}, error data is ${err.data}`)
// ...
}) Close the file and session, and release resources.
fileIo.closeSync(file.fd); session.close();