Problem Description
When downloading a file URL, it is necessary to know the file type for previewing the file, and the file name to determine if a duplicate file exists. Some download links directly display the file name, while others, due to security or storage mechanisms, cannot directly display the file name and instead provide the file request address. How can the file name be obtained during the download process?
Background Knowledge
- The ohos.request module primarily provides applications with basic capabilities for uploading and downloading files, as well as backend transfer proxying.
- getTaskInfo(): The Promise interface queries information about download tasks. It is an asynchronous method that returns information from DownloadInfo using a Promise.
- DownloadInfo contains download task information such as filename information.
Solution
During the download task using request.downloadFile(), use the downloadTask.getTaskInfo() interface to obtain DownloadInfo information, thereby getting the filename fileName. Example code is as follows:
import { BusinessError, request } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
build() {
RelativeContainer() {
Text('Hello World')
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
let context = this.getUIContext().getHostContext();
try {
// You need to manually replace the URL with the actual HTTP address of the server.
request.downloadFile(context, { url: 'xxx.xxx.xxx' }).then((data: request.DownloadTask) => {
let downloadTask: request.DownloadTask = data;
downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => {
console.info('Succeeded in querying the download task');
console.info(`filename: ${downloadInfo.fileName}`);
}).catch((err: BusinessError) => {
console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`);
});
}).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)}`);
}
});
}
.height('100%')
.width('100%');
}
}
Verification Result
- This example supports API Version 17 Release and above.
- This example supports HarmonyOS 5.1.0 Release SDK and above.
- This example requires DevEco Studio 5.1.0 Release and above to compile and run.
- Permission request: ohos.permission.INTERNET .
Reference Link
- https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-request#gettaskinfo9
- https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-request#downloadinfo7
Top comments (0)