harmony 鸿蒙@ohos.request (Upload and Download)

2022-08-09 浏览 (1111)

@ohos.request (Upload and Download)

The request module provides applications with basic upload, download, and background transmission agent capabilities.

NOTE

The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import request from '@ohos.request';

Constants

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Network Types

You can set networkType in DownloadConfig to specify the network type for the download service.

NameTypeValueDescription
NETWORK_MOBILEnumber0x00000001Whether download is allowed on a mobile network.
NETWORK_WIFInumber0x00010000Whether download is allowed on a WLAN.

Download Error Codes

The table below lists the values of err in the callback of on('fail')7+ and the values of failedReason returned by getTaskInfo9+.

NameTypeValueDescription
ERROR_CANNOT_RESUME7+number0Failure to resume the download due to network errors.
ERROR_DEVICE_NOT_FOUND7+number1Failure to find a storage device such as a memory card.
ERROR_FILE_ALREADY_EXISTS7+number2Failure to download the file because it already exists.
ERROR_FILE_ERROR7+number3File operation failure.
ERROR_HTTP_DATA_ERROR7+number4HTTP transmission failure.
ERROR_INSUFFICIENT_SPACE7+number5Insufficient storage space.
ERROR_TOO_MANY_REDIRECTS7+number6Error caused by too many network redirections.
ERROR_UNHANDLED_HTTP_CODE7+number7Unidentified HTTP code.
ERROR_UNKNOWN7+number8Unknown error.
ERROR_OFFLINE9+number9No network connection.
ERROR_UNSUPPORTED_NETWORK_TYPE9+number10Network type mismatch.

Causes of Download Pause

The table below lists the values of pausedReason returned by getTaskInfo9+.

NameTypeValueDescription
PAUSED_QUEUED_FOR_WIFI7+number0Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.
PAUSED_WAITING_FOR_NETWORK7+number1Download paused due to a network connection problem, for example, network disconnection.
PAUSED_WAITING_TO_RETRY7+number2Download paused and then retried.
PAUSED_BY_USER9+number3The user paused the session.
PAUSED_UNKNOWN7+number4Download paused due to unknown reasons.

Download Task Status Codes

The table below lists the values of status returned by getTaskInfo9+.

NameTypeValueDescription
SESSION_SUCCESSFUL7+number0Successful download.
SESSION_RUNNING7+number1Download in progress.
SESSION_PENDING7+number2Download pending.
SESSION_PAUSED7+number3Download paused.
SESSION_FAILED7+number4Download failure without retry.

request.uploadFile9+

uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask>

Uploads files. This API uses a promise to return the result. You can use on('complete'|'fail')9+ to obtain the upload error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
contextBaseContextYesApplication-based context.
configUploadConfigYesUpload configurations.

Return value

TypeDescription
Promise<UploadTask>Promise used to return the UploadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400002bad file path.

Example

let uploadTask: request.UploadTask;
let uploadConfig: request.UploadConfig = {
  url: 'http://www.example.com', // Replace the example with the actual server address.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
  data: [{ name: "name123", value: "123" }],
};
try {
  request.uploadFile(this.context, uploadConfig).then((data: request.UploadTask) => {
    uploadTask = data;
  }).catch((err: BusinessError) => {
    console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.uploadFile9+

uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void

Uploads files. This API uses an asynchronous callback to return the result. You can use on('complete'|'fail')9+ to obtain the upload error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
contextBaseContextYesApplication-based context.
configUploadConfigYesUpload configurations.
callbackAsyncCallback<UploadTask>YesCallback used to return the UploadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400002bad file path.

Example

let uploadTask: request.UploadTask;
let uploadConfig: request.UploadConfig = {
  url: 'http://www.example.com', // Replace the example with the actual server address.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
  data: [{ name: "name123", value: "123" }],
};
try {
  request.uploadFile(this.context, uploadConfig, (err: BusinessError, data: request.UploadTask) => {
    if (err) {
      console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    uploadTask = data;
  });
} catch (err) {
  console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.upload(deprecated)

upload(config: UploadConfig): Promise<UploadTask>

Uploads files. This API uses a promise to return the result.

Model restriction: This API can be used only in the FA model.

NOTE

This API is deprecated since API version 9. You are advised to use request.uploadFile9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
configUploadConfigYesUpload configurations.

Return value

TypeDescription
Promise<UploadTask>Promise used to return the UploadTask object.

Example

let uploadTask;
let uploadConfig = {
  url: 'http://www.example.com', // Replace the example with the actual server address.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
  data: [{ name: "name123", value: "123" }],
};
request.upload(uploadConfig).then((data) => {
  uploadTask = data;
}).catch((err) => {
  console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
})

request.upload(deprecated)

upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void

Uploads files. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the FA model.

NOTE

This API is deprecated since API version 9. You are advised to use request.uploadFile9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
configUploadConfigYesUpload configurations.
callbackAsyncCallback<UploadTask>YesCallback used to return the UploadTask object.

Example

let uploadTask;
let uploadConfig = {
  url: 'http://www.example.com', // Replace the example with the actual server address.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
  data: [{ name: "name123", value: "123" }],
};
request.upload(uploadConfig, (err, data) => {
  if (err) {
    console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  uploadTask = data;
});

UploadTask

Implements file uploads. Before using any APIs of this class, you must obtain an UploadTask object through request.uploadFile9+ in promise mode or request.uploadFile9+ in callback mode.

on('progress')

on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void

Subscribes to upload progress events. This API uses a callback to return the result synchronously.

NOTE

To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value is 'progress' (upload progress).
callbackfunctionYesCallback for the upload progress event.

Parameters of the callback function

NameTypeMandatoryDescription
uploadedSizenumberYesSize of the uploaded files, in bytes.
totalSizenumberYesTotal size of the files to upload, in bytes.

Example

let upProgressCallback = (uploadedSize: number, totalSize: number) => {
  console.info("upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize);
};
uploadTask.on('progress', upProgressCallback);

on('headerReceive')7+

on(type: 'headerReceive', callback: (header: object) => void): void

Subscribes to HTTP header events for an upload task. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value is 'headerReceive' (response header).
callbackfunctionYesCallback for the HTTP Response Header event.

Parameters of the callback function

NameTypeMandatoryDescription
headerobjectYesHTTP Response Header.

Example

let headerCallback = (headers: object) => {
  console.info("upOnHeader headers:" + JSON.stringify(headers));
};
uploadTask.on('headerReceive', headerCallback);

on('complete'|'fail')9+

on(type:'complete'|'fail', callback: Callback<Array<TaskState>>): void;

Subscribes to upload completion or failure events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value 'complete' means the upload completion event, and 'fail' means the upload failure event.
callbackCallback<Array<TaskState>>YesCallback used to return the result.

Parameters of the callback function

NameTypeMandatoryDescription
taskstatesArray<TaskState>YesUpload result.

Example

let upCompleteCallback = (taskStates: Array<request.TaskState>) => {
  for (let i = 0; i < taskStates.length; i++) {
    console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
  }
};
uploadTask.on('complete', upCompleteCallback);

let upFailCallback = (taskStates: Array<request.TaskState>) => {
  for (let i = 0; i < taskStates.length; i++) {
    console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
  }
};
uploadTask.on('fail', upFailCallback);

off('progress')

off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void

Unsubscribes from upload progress events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to unsubscribe from. The value is 'progress' (upload progress).
callbackfunctionNoCallback used to return the result.
uploadedSize: size of the uploaded files, in B.
totalSize: Total size of the files to upload, in B.

Example

let upProgressCallback = (uploadedSize: number, totalSize: number) => {
  console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize);
};
uploadTask.off('progress', upProgressCallback);

off('headerReceive')7+

off(type: 'headerReceive', callback?: (header: object) => void): void

Unsubscribes from HTTP header events for an upload task. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to unsubscribe from. The value is 'headerReceive' (response header).
callbackfunctionNoCallback used to return the result.
header: HTTP response header.

Example

let headerCallback = (header: object) => {
  console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`);
};
uploadTask.off('headerReceive', headerCallback);

off('complete'|'fail')9+

off(type:'complete'|'fail', callback?: Callback<Array<TaskState>>): void;

Unsubscribes from upload completion or failure events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value 'complete' means the upload completion event, and 'fail' means the upload failure event.
callbackCallback<Array<TaskState>>NoCallback used to return the result.
taskstates: upload task result.

Example

let upCompleteCallback = (taskStates: Array<request.TaskState>) => {
  console.info('Upload delete complete notification.');
  for (let i = 0; i < taskStates.length; i++) {
    console.info('taskState:' + JSON.stringify(taskStates[i]));
  }
};
uploadTask.off('complete', upCompleteCallback);

let upFailCallback = (taskStates: Array<request.TaskState>) => {
  console.info('Upload delete fail notification.');
  for (let i = 0; i < taskStates.length; i++) {
    console.info('taskState:' + JSON.stringify(taskStates[i]));
  }
};
uploadTask.off('fail', upFailCallback);

delete9+

delete(): Promise<boolean>

Deletes this upload task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Return value

TypeDescription
Promise<boolean>Promise used to return the task removal result. It returns true if the operation is successful and returns false otherwise.

Example

uploadTask.delete().then((result: boolean) => {
  console.info('Succeeded in deleting the upload task.');
}).catch((err: BusinessError) => {
  console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
});

delete9+

delete(callback: AsyncCallback<boolean>): void

Deletes this upload task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result.

Example

uploadTask.delete((err: BusinessError, result: boolean) => {
  if (err) {
    console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in deleting the upload task.');
});

remove(deprecated)

remove(): Promise<boolean>

Removes this upload task. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Return value

TypeDescription
Promise<boolean>Promise used to return the task removal result. It returns true if the operation is successful and returns false otherwise.

Example

uploadTask.remove().then((result) => {
  console.info('Succeeded in removing the upload task.');
}).catch((err) => {
  console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
});

remove(deprecated)

remove(callback: AsyncCallback<boolean>): void

Removes this upload task. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result.

Example

uploadTask.remove((err, result) => {
  if (err) {
    console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  if (result) {
    console.info('Succeeded in removing the upload task.');
  } else {
    console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
  }
});

UploadConfig

Describes the configuration for an upload task.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

NameTypeMandatoryDescription
urlstringYesResource URL.
headerObjectYesHTTP or HTTPS header added to an upload request.
methodstringYesRequest method, which can be 'POST' or 'PUT'. The default value is 'POST'.
filesArray<File>YesList of files to upload, which is submitted through multipart/form-data.
dataArray<RequestData>YesForm data in the request body.

TaskState9+

Implements a TaskState object, which is the callback parameter of the on('complete'|'fail')9+ and off('complete'|'fail')9+ APIs.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

NameTypeMandatoryDescription
pathstringYesFile path.
responseCodenumberYesReturn value of an upload task. The value 0 means that the task is successful, and other values means that the task fails. For details about the task result, see message.
messagestringYesDescription of the upload task result.

File

Describes the list of files in UploadConfig.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

NameTypeMandatoryDescription
filenamestringYesFile name in the header when multipart is used.
namestringYesName of a form item when multipart is used. The default value is file.
uristringYesLocal path for storing files.
Only the internal protocol type is supported. In the value, "internal://cache/" must be included. Example:
internal://cache/path/to/file.txt
typestringYesType of the file content. By default, the type is obtained based on the extension of the file name or URI.

RequestData

Describes the form data in UploadConfig.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

NameTypeMandatoryDescription
namestringYesName of a form element.
valuestringYesValue of a form element.

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask>

Downloads files. This API uses a promise to return the result. You can use on('complete'|'pause'|'remove')7+ to obtain the download task state, which can be completed, paused, or removed. You can also use on('fail')7+ to obtain the task download error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
contextBaseContextYesApplication-based context.
configDownloadConfigYesDownload configurations.

Return value

TypeDescription
Promise<DownloadTask>Promise used to return the result.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400001file operation error.
13400002bad file path.
13400003task service ability error.

Example

let downloadTask: request.DownloadTask;
try {
  request.downloadFile(this.context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    downloadTask = data;
  }).catch((err: BusinessError) => {
    console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
  })
} catch (err) {
  console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void;

Downloads files. This API uses an asynchronous callback to return the result. You can use on('complete'|'pause'|'remove')7+ to obtain the download task state, which can be completed, paused, or removed. You can also use on('fail')7+ to obtain the task download error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
contextBaseContextYesApplication-based context.
configDownloadConfigYesDownload configurations.
callbackAsyncCallback<DownloadTask>YesCallback used to return the result.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400001file operation error.
13400002bad file path.
13400003task service ability error.

Example

let downloadTask: request.DownloadTask;
try {
  request.downloadFile(this.context, {
    url: 'https://xxxx/xxxxx.hap',
    filePath: 'xxx/xxxxx.hap'
  }, (err: BusinessError, data: request.DownloadTask) => {
    if (err) {
      console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    downloadTask = data;
  });
} catch (err) {
  console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.download(deprecated)

download(config: DownloadConfig): Promise<DownloadTask>

Downloads files. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use request.downloadFile9+ instead.

Model restriction: This API can be used only in the FA model.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
configDownloadConfigYesDownload configurations.

Return value

TypeDescription
Promise<DownloadTask>Promise used to return the result.

Example

let downloadTask;
request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => {
  downloadTask = data;
}).catch((err) => {
  console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
})

request.download(deprecated)

download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void

Downloads files. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use request.downloadFile9+ instead.

Model restriction: This API can be used only in the FA model.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
configDownloadConfigYesDownload configurations.
callbackAsyncCallback<DownloadTask>YesCallback used to return the result.

Example

let downloadTask;
request.download({ url: 'https://xxxx/xxxxx.hap', 
filePath: 'xxx/xxxxx.hap'}, (err, data) => {
  if (err) {
    console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  downloadTask = data;
});

DownloadTask

Implements file downloads. Before using any APIs of this class, you must obtain a DownloadTask object through request.downloadFile9+ in promise mode or request.downloadFile9+ in callback mode.

on('progress')

on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void

Subscribes to download progress events. This API uses a callback to return the result synchronously.

NOTE

To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value is 'progress' (download progress).
callbackfunctionYesCallback used to return the result.

Parameters of the callback function

NameTypeMandatoryDescription
receivedSizenumberYesSize of the downloaded files, in bytes.
totalSizenumberYesTotal size of the files to download, in bytes.

Example

let progresCallback = (receivedSize: number, totalSize: number) => {
  console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
};
downloadTask.on('progress', progresCallback);

off('progress')

off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void

Unsubscribes from download progress events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to unsubscribe from. The value is 'progress' (download progress).
callbackfunctionNoCallback used to return the result.
receivedSize: size of the downloaded files.
totalSize: total size of the files to download.

Example

let progresCallback = (receivedSize: number, totalSize: number) => {
  console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize);
};
downloadTask.off('progress', progresCallback);

on('complete'|'pause'|'remove')7+

on(type: 'complete'|'pause'|'remove', callback:() => void): void

Subscribes to download events. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to.
- 'complete': download task completion event.
- 'pause': download task pause event.
- 'remove': download task removal event.
callbackfunctionYesCallback used to return the result.

Example

let completeCallback = () => {
  console.info('Download task completed.');
};
downloadTask.on('complete', completeCallback);

let pauseCallback = () => {
  console.info('Download task pause.');
};
downloadTask.on('pause', pauseCallback);

let removeCallback = () => {
  console.info('Download task remove.');
};
downloadTask.on('remove', removeCallback);

off('complete'|'pause'|'remove')7+

off(type: 'complete'|'pause'|'remove', callback?:() => void): void

Unsubscribes from download events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to unsubscribe from.
- 'complete': download task completion event.
- 'pause': download task pause event.
- 'remove': download task removal event.
callbackfunctionNoCallback used to return the result.

Example

let completeCallback = () => {
  console.info('Download delete complete notification.');
};
downloadTask.off('complete', completeCallback);

let pauseCallback = () => {
  console.info('Download delete pause notification.');
};
downloadTask.off('pause', pauseCallback);

let removeCallback = () => {
  console.info('Download delete remove notification.');
};
downloadTask.off('remove', removeCallback);

on('fail')7+

on(type: 'fail', callback: (err: number) => void): void

Subscribes to download failure events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to subscribe to. The value is 'fail' (download failure).
callbackfunctionYesCallback for the download task failure event.

Parameters of the callback function

NameTypeMandatoryDescription
errnumberYesError code of the download failure. For details about the error codes, see Download Error Codes.

Example

let failCallback = (err: BusinessError) => {
  console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`);
};
downloadTask.on('fail', failCallback);

off('fail')7+

off(type: 'fail', callback?: (err: number) => void): void

Unsubscribes from download failure events. This API uses a callback to return the result synchronously.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
typestringYesType of the event to unsubscribe from. The value is 'fail' (download failure).
callbackfunctionNoCallback used to return the result.
err: error code of the download failure.

Example

let failCallback = (err: BusinessError) => {
  console.error(`Failed to download the task. Code: ${err.code}, message: ${err.message}`);
};
downloadTask.off('fail', failCallback);

delete9+

delete(): Promise<boolean>

Removes this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<boolean>Promise used to return the task removal result.

Example

downloadTask.delete().then((result: boolean) => {
  console.info('Succeeded in removing the download task.');
}).catch((err: BusinessError) => {
  console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
});

delete9+

delete(callback: AsyncCallback<boolean>): void

Deletes this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the task deletion result.

Example

downloadTask.delete((err: BusinessError, result: boolean) => {
  if (err) {
    console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in removing the download task.');
});

getTaskInfo9+

getTaskInfo(): Promise<DownloadInfo>

Obtains the information about this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<DownloadInfo>Promise used to return the download task information.

Example

downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => {
  console.info('Succeeded in querying the download task')
}).catch((err: BusinessError) => {
  console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
});

getTaskInfo9+

getTaskInfo(callback: AsyncCallback<DownloadInfo>): void

Obtains the information about this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<DownloadInfo>YesCallback used to return the download task information.

Example

downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => {
  if (err) {
    console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
  } else {
    console.info('Succeeded in querying the download mimeType');
  }
});

getTaskMimeType9+

getTaskMimeType(): Promise<string>

Obtains the MimeType of this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<string>Promise used to return the MimeType of the download task.

Example

downloadTask.getTaskMimeType().then((data: string) => {
  console.info('Succeeded in querying the download MimeType');
}).catch((err: BusinessError) => {
  console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
});

getTaskMimeType9+

getTaskMimeType(callback: AsyncCallback<string>): void;

Obtains the MimeType of this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<string>YesCallback used to return the MimeType of the download task.

Example

downloadTask.getTaskMimeType((err: BusinessError, data: string) => {
  if (err) {
    console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
  } else {
    console.info('Succeeded in querying the download mimeType');
  }
});

suspend9+

suspend(): Promise<boolean>

Pauses this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<boolean>Promise used to return the download task pause result.

Example

downloadTask.suspend().then((result: boolean) => {
  console.info('Succeeded in pausing the download task.');
}).catch((err: BusinessError) => {
  console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
});

suspend9+

suspend(callback: AsyncCallback<boolean>): void

Pauses this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result.

Example

downloadTask.suspend((err: BusinessError, result: boolean) => {
  if (err) {
    console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in pausing the download task.');
});

restore9+

restore(): Promise<boolean>

Resumes this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<boolean>Promise used to return the result.

Example

downloadTask.restore().then((result: boolean) => {
  console.info('Succeeded in resuming the download task.')
}).catch((err: BusinessError) => {
  console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
});

restore9+

restore(callback: AsyncCallback<boolean>): void

Resumes this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result.

Example

downloadTask.restore((err: BusinessError, result: boolean) => {
  if (err) {
    console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in resuming the download task.');
});

remove(deprecated)

remove(): Promise<boolean>

Removes this download task. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<boolean>Promise used to return the task removal result.

Example

downloadTask.remove().then((result) => {
  console.info('Succeeded in removing the download task.');
}).catch ((err) => {
  console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
});

remove(deprecated)

remove(callback: AsyncCallback<boolean>): void

Removes this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the task deletion result.

Example

downloadTask.remove((err, result)=>{
  if(err) {
    console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in removing the download task.');
});

query(deprecated)

query(): Promise<DownloadInfo>

Queries this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use getTaskInfo9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<DownloadInfo>Promise used to return the download task information.

Example

downloadTask.query().then((downloadInfo) => {    
  console.info('Succeeded in querying the download task.')
}) .catch((err) => {
  console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
});

query(deprecated)

query(callback: AsyncCallback<DownloadInfo>): void

Queries this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use getTaskInfo9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<DownloadInfo>YesCallback used to return the download task information.

Example

downloadTask.query((err, downloadInfo)=>{
  if(err) {
    console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
  } else {
    console.info('Succeeded in querying the download task.');
  }
});

queryMimeType(deprecated)

queryMimeType(): Promise<string>

Queries the MimeType of this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use getTaskMimeType9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<string>Promise used to return the MimeType of the download task.

Example

downloadTask.queryMimeType().then((data) => {    
  console.info('Succeededto in querying the download MimeType.');
}).catch((err) => {
  console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
});

queryMimeType(deprecated)

queryMimeType(callback: AsyncCallback<string>): void;

Queries the MimeType of this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use getTaskMimeType9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<string>YesCallback used to return the MimeType of the download task.

Example

downloadTask.queryMimeType((err, data)=>{
  if(err) {
    console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
  } else {
    console.info('Succeeded in querying the download mimeType.');
  }
});

pause(deprecated)

pause(): Promise<void>

Pauses this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use suspend9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<void>Promise used to return the download task pause result.

Example

downloadTask.pause().then((result) => {    
  console.info('Succeeded in pausing the download task.');
}).catch((err) => {
  console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
});

pause(deprecated)

pause(callback: AsyncCallback<void>): void

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use suspend9+ instead.

Pauses this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

downloadTask.pause((err, result)=>{
  if(err) {
    console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in pausing the download task.');
});

resume(deprecated)

resume(): Promise<void>

Resumes this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use restore9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

downloadTask.resume().then((result) => {
  console.info('Succeeded in resuming the download task.')
}).catch((err) => {
  console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
});

resume(deprecated)

resume(callback: AsyncCallback<void>): void

NOTE

This API is supported since API version 7 and is deprecated since API version 9. You are advised to use restore9+ instead.

Resumes this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

downloadTask.resume((err, result)=>{
  if (err) {
    console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in resuming the download task.');
});

DownloadConfig

Defines the download task configuration.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

NameTypeMandatoryDescription
urlstringYesResource URL.
headerObjectNoHTTPS flag header to be included in the download request.
The X-TLS-Version parameter in header specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
The X-Cipher-List parameter in header specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:
- The TLS 1.2 cipher suite list includes the following ciphers:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- The TLS 1.3 cipher suite list includes the following ciphers:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3
enableMeteredbooleanNoWhether download is allowed on a metered connection. The default value is false. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.
- true: allowed
- false: not allowed
enableRoamingbooleanNoWhether download is allowed on a roaming network. The default value is false.
- true: allowed
- false: not allowed
descriptionstringNoDescription of the download session.
filePath7+stringNoPath where the downloaded file is stored.
- In the FA model, use context to obtain the cache directory of the application, for example, **${featureAbility.getContext().getFilesDir()}/test.txt*, and store the file in this directory.
- In the stage model, use AbilityContext to obtain the file path, for example, **${globalThis.abilityContext.tempDir}/test.txt*
, and store the file in this path.
networkTypenumberNoNetwork type allowed for the download. The default value is NETWORK_MOBILE and NETWORK_WIFI.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000
titlestringNoDownload task name.
background9+booleanNoWhether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.

DownloadInfo7+

Defines the download task information, which is the callback parameter of the getTaskInfo9+ API.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

NameTypeMandatoryDescription
downloadIdnumberYesID of the download task.
failedReasonnumberYesCause of the download failure. The value can be any constant in Download Error Codes.
fileNamestringYesName of the downloaded file.
filePathstringYesURI of the saved file.
pausedReasonnumberYesCause of download pause. The value can be any constant in Causes of Download Pause.
statusnumberYesDownload task status code. The value can be any constant in Download Task Status Codes.
targetURIstringYesURI of the downloaded file.
downloadTitlestringYesName of the download task.
downloadTotalBytesnumberYesTotal size of the files to download, in bytes.
descriptionstringYesDescription of the download task.
downloadedBytesnumberYesSize of the files downloaded, in bytes.

Action10+

Defines action options.

System capability: SystemCapability.Request.FileTransferAgent

NameValueDescription
DOWNLOAD0Download.
UPLOAD1Upload.

Mode10+

Defines mode options.

System capability: SystemCapability.Request.FileTransferAgent

NameValueDescription
BACKGROUND0Background task.
FOREGROUND1Foreground task.

Network10+

Defines network options.

System capability: SystemCapability.Request.FileTransferAgent

NameValueDescription
ANY0Network of any type.
WIFI1Wi-Fi network.
CELLULAR2Cellular data network.

FileSpec10+

Provides the file information of a table item.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
pathstringYesRelative path in the cache folder of the invoker.
mimeTypestringNoMIME type of the file, which is obtained from the file name.
filenamestringNoFile name. The default value is obtained from the file path.
extrasObjectNoAdditional information of the file.

FormItem10+

Describes the form item of a task.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
namestringYesForm parameter name.
valuestring |FileSpec |Array<FileSpec>YesForm parameter value.

Config10+

Provides the configuration information of an upload or download task.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
actionActionYesTask action.
- UPLOAD
- DOWNLOAD
urlstringYesResource URL. The value contains a maximum of 2048 characters.
titlestringNoTask title. The value contains a maximum of 256 characters. The default value is a null string.
descriptionstringNoTask description. The value contains a maximum of 1024 characters. The default value is a null string.
modeModeNoTask mode. The default mode is background.
- For a foreground task, a callback is used for notification.
- For a background task, the system notification and network connection features (detection, recovery, and automatic retry) are provided.
overwritebooleanNoWhether to overwrite an existing file during the download. The default value is false.
- true: Overwrite the existing file.
- false: Do not overwrite the existing file. In this case, the download fails.
methodstringNoStandard HTTP method for the task. The value can be GET, POST, or PUT, which is case-insensitive.
- If the task is an upload, use PUT or POST. The default value is PUT.
- If the task is a download, use GET or POST. The default value is GET.
headersobjectNoHTTP headers to be included in the task.
- If the task is an upload, the default Content-Type is multipart/form-data.
- If the task is a download, the default Content-Type is application/json.
datastring |Array<FormItem>NoTask data.
- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- If the task is an upload, the value is Array<FormItem>; the default value is null.
saveasstringNoPath for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, "./xxx/yyy/zzz.html" and "xxx/yyy/zzz.html".
- URI (applicable when the application has the permission to access the URI), for example, "datashare://bundle/xxx/yyy/zzz.html". This option is not supported currently.
The default value is a relative path in the cache folder of the application.
networkNetworkNoNetwork used for the task. The default value is ANY (Wi-Fi or cellular).
meteredbooleanNoWhether the task is allowed on a metered connection. The default value is false.
- true: The task is allowed on a metered connection.
- false: The task is not allowed on a metered connection.
roamingbooleanNoWhether the task is allowed on a roaming network. The default value is true.
- true: The task is allowed on a roaming network.
- false: The task is not allowed on a roaming network.
retrybooleanNoWhether automatic retry is enabled for the task. This parameter is only applicable to background tasks. The default value is true.
- true: Automatic retry is enabled for the task.
- -false: Automatic retry is not enabled for the task.
redirectbooleanNoWhether redirection is allowed. The default value is true.
- true: Redirection is allowed.
- false: Redirection is not allowed.
indexnumberNoPath index of the task. It is usually used for resumable downloads. The default value is 0.
beginsnumberNoFile start point of the task. It is usually used for resumable downloads. The default value is 0. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.
- If the task is an upload, the value is obtained at the beginning of the upload.
endsnumberNoFile end point of the task. It is usually used for resumable downloads. The default value is -1. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.
- If the task is an upload, the value is obtained at the end of the upload.
gaugebooleanNoWhether to send progress notifications. This parameter applies only to background tasks. The default value is false.
- false: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.
- true: Progress notifications are sent to indicate the result of each file.
precisebooleanNo- If this parameter is set to true, the task fails when the file size cannot be obtained.
- If this parameter is set to false, the task continues when the file size is set to -1.
The default value is false.
tokenstringNoToken of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.
extrasobjectNoAdditional information of the task. This parameter is left empty by default.

State10+

Defines the current task status.

System capability: SystemCapability.Request.FileTransferAgent

NameValueDescription
INITIALIZED0x00The task is initialized based on the configuration specified in Config.
WAITING0x10The task lacks resources for running or the resources for retries do not match the network status.
RUNNING0x20The task is being executed.
RETRYING0x21The task has failed at least once and is being executed again.
PAUSED0x30The task is suspended and will be resumed later.
STOPPED0x31The task is stopped.
COMPLETED0x40The task is complete.
FAILED0x41The task fails.
REMOVED0x50The task is removed.

Progress10+

Describes the data structure of the task progress.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
stateStateYesCurrent task status.
indexnumberYesIndex of the file that is being processed in the task.
processednumberYesSize of processed data in the current file in the task, in bytes.
sizesArray<number>YesSize of files in the task, in bytes.
extrasobjectNoExtra information of the task, for example, the header and body of the response from the server.

Faults10+

Defines the cause of a task failure.

System capability: SystemCapability.Request.FileTransferAgent

NameValueDescription
OTHERS0xFFOther fault.
DISCONNECTED0x00Network disconnection.
TIMEOUT0x10Timeout.
PROTOCOL0x20Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416).
FSIO0x40File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation.

Filter10+

Defines the filter criteria.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
bundlestringNoBundle name of an application.
System API: This is a system API.
beforenumberNoUnix timestamp of the end time, in milliseconds. The default value is the invoking time.
afternumberNoUnix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours.
stateStateNoTask state.
actionActionNoTask action.
- UPLOAD
- DOWNLOAD
modeModeNoTask mode.
- FOREGROUND
- BACKGROUND

TaskInfo10+

Defines the data structure of the task information for query. The fields available vary depending on the query type.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
uidstringNoUID of the application. It is only available for query by system applications.
System API: This is a system API.
bundlestringNoBundle name of the application. It is only available for query by system applications.
System API: This is a system API.
saveasstringNoPath for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, "./xxx/yyy/zzz.html" and "xxx/yyy/zzz.html".
- URI (applicable when the application has the permission to access the URI), for example, "datashare://bundle/xxx/yyy/zzz.html". This option is not supported currently.
The default value is a relative path in the cache folder of the application.
urlstringNoTask URL.
- It can be obtained through request.agent.show10+, request.agent.touch10+, or request.agent.query10+. When request.agent.query10+ is used, an empty string is returned.
datastring |Array<FormItem>NoTask value.
- It can be obtained through request.agent.show10+, request.agent.touch10+, or request.agent.query10+. When request.agent.query10+ is used, an empty string is returned.
tidstringYesTask ID.
titlestringYesTask title.
descriptionstringYesTask description.
actionActionYesTask action.
- UPLOAD
- DOWNLOAD
modeModeYesTask mode.
- FOREGROUND
- BACKGROUND
mimeTypestringYesMIME type in the task configuration.
progressProgressYesTask progress.
gaugebooleanYesWhether to send progress notifications. This parameter applies only to background tasks.
ctimenumberYesUnix timestamp when the task is created, in milliseconds. The value is generated by the system of the current device.
Note: When request.agent.search10+ is used for query, this value must be within the range of [after,before] for the task ID to be obtained. For details about before and after, see Filter.
mtimenumberYesUnix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device.
retrybooleanYesWhether automatic retry is enabled for the task. This parameter applies only to background tasks.
triesnumberYesNumber of retries of the task.
faultsFaultsYesFailure cause of the task.
- OTHERS: other fault.
- DISCONNECT: network disconnection.
- TIMEOUT: timeout.
- PROTOCOL: protocol error.
- FSIO: file system I/O error.
reasonstringYesReason why the task is waiting, failed, stopped, or paused.
extrasstringNoExtra information of the task

Task10+

Implements an upload or download task. Before using this API, you must obtain a Task object, from a promise through request.agent.create10+ or from a callback through request.agent.create10+.

Attributes

Task attributes include the task ID and task configuration.

System capability: SystemCapability.Request.FileTransferAgent

NameTypeMandatoryDescription
tidstringYesTask ID, which is unique in the system and is automatically generated by the system.
configConfigYesTask configuration.

on('progress')10+

on(event: 'progress', callback: (progress: Progress) => void): void

Subscribes to foreground task progress changes.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'progress', indicating the task progress.
callbackfunctionYesCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOnTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOnCallback = (progress: request.agent.Progress) => {
  console.info('upload task progress.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('progress', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('completed')10+

on(event: 'completed', callback: (progress: Progress) => void): void

Subscribes to the foreground task completion event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'completed', indicating task completion.
callbackfunctionYesCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOnTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOnCallback = (progress: request.agent.Progress) => {
  console.info('upload task completed.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('completed', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('failed')10+

on(event: 'failed', callback: (progress: Progress) => void): void

Subscribes to the foreground task failure event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'failed', indicating task failure.
callbackfunctionYesCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOnTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOnCallback = (progress: request.agent.Progress) => {
  console.info('upload task failed.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('failed', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('progress')10+

off(event: 'progress', callback?: (progress: Progress) => void): void

Unsubscribes from foreground task progress changes.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'progress', indicating the task progress.
callbackfunctionNoCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOffTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOffCallback = (progress: request.agent.Progress) => {
  console.info('upload task progress.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('progress', createOffCallback);
  task.off('progress', createOffCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('completed')10+

off(event: 'completed', callback?: (progress: Progress) => void): void

Unsubscribes from the foreground task completion event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'completed', indicating task completion.
callbackfunctionNoCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOffTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOffCallback = (progress: request.agent.Progress) => {
  console.info('upload task completed.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('completed', createOffCallback);
  task.off('completed', createOffCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('failed')10+

off(event: 'failed', callback?: (progress: Progress) => void): void

Unsubscribes from the foreground task failure event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
eventstringYesType of the event to subscribe to.
The value is 'failed', indicating task failure.
callbackfunctionNoCallback used to return the data structure of the task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    mimeType: "application/octet-stream",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'taskOffTest',
  description: 'Sample code for event listening',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
let createOffCallback = (progress: request.agent.Progress) => {
  console.info('upload task failed.');
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.on('failed', createOffCallback);
  task.off('failed', createOffCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

start10+

start(callback: AsyncCallback<void>): void

Starts this task. This API cannot be used to start an initialized task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
callbackfunctionYesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskStartTest',
  description: 'Sample code for start the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.start((err: BusinessError) => {
    if (err) {
      console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in starting a download task.`);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

start10+

start(): Promise<void>

Starts this task. This API cannot be used to start an initialized task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskStartTest',
  description: 'Sample code for start the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.start().then(() => {
    console.info(`Succeeded in starting a download task.`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

pause10+

pause(callback: AsyncCallback<void>): void

Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
callbackfunctionYesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900005task mode error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskPauseTest',
  description: 'Sample code for pause the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.pause((err: BusinessError) => {
    if (err) {
      console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in pausing a download task. `);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

pause10+

pause(): Promise<void>

Pauses this task. This API can be used to pause a background task that is waiting, running, or retrying. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900005task mode error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskPauseTest',
  description: 'Sample code for pause the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.pause().then(() => {
    console.info(`Succeeded in pausing a download task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to pause the upload task, Code: ${err.code}, message: ${err.message}`);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

resume10+

resume(callback: AsyncCallback<void>): void

Resumes this task. This API can be used to resume a paused background task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
callbackfunctionYesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900005task mode error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskResumeTest',
  description: 'Sample code for resume the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.resume((err: BusinessError) => {
    if (err) {
      console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in resuming a download task. `);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

resume10+

resume(): Promise<void>

Resumes this task. This API can be used to resume a paused background task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900005task mode error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskResumeTest',
  description: 'Sample code for resume the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.resume().then(() => {
    console.info(`Succeeded in resuming a download task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

stop10+

stop(callback: AsyncCallback<void>): void

Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
callbackfunctionYesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskStopTest',
  description: 'Sample code for stop the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.stop((err: BusinessError) => {
    if (err) {
      console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in stopping a download task. `);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

stop10+

stop(): Promise<void>

Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900007task state error.

Example

let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1',
  title: 'taskStopTest',
  description: 'Sample code for stop the download task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "GET",
  data: "",
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  task.stop().then(() => {
    console.info(`Succeeded in stopping a download task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
  });
  console.info(`Succeeded in creating a download task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

request.agent.create10+

create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void

Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
configConfigYesTask configuration.
contextBaseContextYesApplication-based context.
callbackAsyncCallback<Task>YesCallback used to return the configuration about the created task.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400001file operation error.
13400003task service ability error.
21900004application task queue full error.
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "reeateTest",
  value: {
    filename: "reeateTest.avi",
    mimeType: "application/octet-stream",
    path: "./reeateTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'reeateTest',
  description: 'Sample code for reeate task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config, (err: BusinessError, task: request.agent.Task) => {
  if (err) {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in creating a download task. result: ${task.config}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.agent.create10+

create(context: BaseContext, config: Config): Promise<Task>

Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
contextBaseContextYesApplication-based context.
configConfigYesTask configuration.

Return value

TypeDescription
Promise<Task>Promise used to return the configuration about the created task.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400001file operation error.
13400003task service ability error.
21900004application task queue full error.
21900005task mode error.

Example

let attachments: Array<request.agent.FormItem> = [{
  name: "reeateTest",
  value: {
    filename: "reeateTest.avi",
    mimeType: "application/octet-stream",
    path: "./reeateTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1',
  title: 'reeateTest',
  description: 'Sample code for reeate task',
  mode: request.agent.Mode.BACKGROUND,
  overwrite: false,
  method: "PUT",
  data: attachments,
  saveas: "./",
  network: request.agent.Network.CELLULAR,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: "it is a secret"
};
request.agent.create(this.context, config).then((task: request.agent.Task) => {
  console.info(`Succeeded in creating a download task. result: ${task.config}`);
}).catch((err) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.agent.remove10+

remove(id: string, callback: AsyncCallback<void>): void

Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.remove("id", (err: BusinessError) => {
  if (err) {
    console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in creating a download task.`);
});

request.agent.remove10+

remove(id: string): Promise<void>

Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.remove("id").then(() => {
  console.info(`Succeeded in removing a download task. `);
}).catch((err: BusinessError) => {
  console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`);
});

request.agent.show10+

show(id: string, callback: AsyncCallback<TaskInfo>): void

Shows the task details based on the task ID. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.
callbackAsyncCallback<TaskInfo>YesCallback used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
  if (err) {
    console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in showing an upload task.`);
});

request.agent.show10+

show(id: string): Promise<TaskInfo>

Queries a task details based on the task ID. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.

Return value

TypeDescription
Promise<TaskInfo>Promise Promise used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => {
  console.info(`Succeeded in showing an upload task.`);
}).catch((err: BusinessError) => {
  console.error(`Failed to show an upload task, Code: ${err.code}, message: ${err.message}`);
});

request.agent.touch10+

touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void

Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.
tokenstringYesToken for task query.
callbackAsyncCallback<TaskInfo>YesCallback used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
  if (err) {
    console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in touching an upload task.`);
});

request.agent.touch10+

touch(id: string, token: string): Promise<TaskInfo>

Queries the task details based on the task ID and token. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.
tokenstringYesToken for task query.

Return value

TypeDescription
Promise<TaskInfo>Promise Promise used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => {
  console.info(`Succeeded in touching a upload task. `);
}).catch((err: BusinessError) => {
  console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`);
});

request.agent.search10+

search(callback: AsyncCallback<Array<string>>): void

Searches for task IDs based on Filter. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Array<string>>YesCallback used to return task ID matches.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.

Example

request.agent.search((err: BusinessError, data: Array<string>) => {
  if (err) {
    console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Upload task search succeeded. `);
});

request.agent.search10+

search(filter: Filter, callback: AsyncCallback<Array<string>>): void

Searches for task IDs based on Filter. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
filterFilterYesFilter criteria.
callbackAsyncCallback<Array<string>>YesCallback used to return task ID matches.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.

Example

let filter: request.agent.Filter = {
  bundle: "com.example.myapplication",
  action: request.agent.Action.UPLOAD,
  mode: request.agent.Mode.BACKGROUND
}
request.agent.search(filter, (err: BusinessError, data: Array<string>) => {
  if (err) {
    console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Upload task search succeeded. `);
});

request.agent.search10+

search(filter?: Filter): Promise<Array<string>>

Searches for task IDs based on Filter. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

NameTypeMandatoryDescription
filterFilterNoFilter criteria.

Return value

TypeDescription
Promise<Array<string>>Promise Promise used to return task ID matches.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.

Example

let filter: request.agent.Filter = {
  bundle: "com.example.myapplication",
  action: request.agent.Action.UPLOAD,
  mode: request.agent.Mode.BACKGROUND
}
request.agent.search(filter).then((data: Array<string>) => {
  console.info(`Upload task search succeeded. `);
}).catch((err: BusinessError) => {
  console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`);
});

request.agent.query10+

query(id: string, callback: AsyncCallback<TaskInfo>): void

Queries the task details based on the task ID. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.DOWNLOAD_SESSION_MANAGER or ohos.permission.UPLOAD_SESSION_MANAGER

System capability: SystemCapability.Request.FileTransferAgent

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.
callbackAsyncCallback<TaskInfo>YesCallback used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.query("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
  if (err) {
    console.error(`Failed to query an upload task. Code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in querying the upload task. Result: ${taskInfo.uid}`);
});

request.agent.query10+

query(id: string): Promise<TaskInfo>

Queries the task details based on the task ID. This API uses a promise to return the result.

Required permissions: ohos.permission.DOWNLOAD_SESSION_MANAGER or ohos.permission.UPLOAD_SESSION_MANAGER

System capability: SystemCapability.Request.FileTransferAgent

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
idstringYesTask ID.

Return value

TypeDescription
Promise<TaskInfo>Promise Promise used to return task details.

Error codes For details about the error codes, see Upload and Download Error Codes.

IDError Message
13400003task service ability error.
21900006task not found error.

Example

request.agent.query("123456",).then((taskInfo: request.agent.TaskInfo) => {
  console.info(`Succeeded in querying the upload task. Result: ${taskInfo.uid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to query the upload task. Code: ${err.code}, message: ${err.message}`);
});

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/2d827a94b9e44fc4926f48c2af1daa00