OpenHarmony开发者论坛
标题:
Axios下载文件示例
[打印本页]
作者:
润开鸿_坚果
时间:
2024-5-8 08:34
标题:
Axios下载文件示例
[md]## Axios下载文件示例
**设置下载路径filePath(默认在'internal://cache/'路径下)。**
> **关于filePath** **filePath:'workspace/test.txt':默认路径下创建workspace路径,并将文件存储在workspace路径下。** **filePath:'test.txt':将文件存储在默认路径下。** **filePath:'workspace/':默认路径下创建workspace路径,并将文件存储在workspace路径下。**
## 完整源码
```
import axios, { AxiosError, AxiosProgressEvent, AxiosResponse } from '@ohos/axios';
import { promptAction } from '@kit.ArkUI';
import fs from '@ohos.file.fs';
@Entry
@Component
struct SecondPage {
@State message: string = 'Hello World';
@State downloadProgress: number = 0
@State status: string | number = ''
@State startTime: number = 0;
@State endTime: number = 0;
aboutToAppear(): void {
this.downLoadFile()
}
downLoadFile() {
this.startTime = new Date().getTime();
let filePath = getContext(this).cacheDir + '/git.pdf'
// 下载。如果文件已存在,则先删除文件。
try {
fs.accessSync(filePath);
fs.unlinkSync(filePath);
} catch (err) {
}
axios({
url: 'https://www.gjtool.cn/pdfh5/git.pdf',
method: 'get',
context: getContext(this),
filePath: filePath,
onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
promptAction.showToast({
message: "下载进度"
})
this.message = JSON.stringify(progressEvent.progress)
console.info("hhhhhhhh" + JSON.stringify(progressEvent))
this.downloadProgress = progressEvent && progressEvent.loaded && progressEvent.total ?
Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0;
// console.info("progress: " + progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
}
}).then((res: AxiosResponse<string>) => {
this.status = res ? res.status : '';
this.message = res ? JSON.stringify(res.data) : '';
this.endTime = new Date().getTime();
}).catch((err: AxiosError) => {
this.status = '';
this.message = err.message;
this.endTime = new Date().getTime();
})
}
build() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Progress({ value: this.downloadProgress, type: ProgressType.Linear })
.color('#009BE8').width('100%')
.margin({ top: 8, right: 10 })
.style({ strokeWidth: 10 })
}
.height('100%')
.width('100%')
}
}
```
## 参考
[axios](
https://gitee.com/openharmony-sig/ohos_axios#axios
)
## 关于坚果派
**坚果派由坚果等人创建,团队拥有 12 个华为 HDE,以及若干其他领域的三十余位万粉博主运营。专注于分享的技术包括 HarmonyOS/OpenHarmony,ArkUI-X,元服务,服务卡片,华为自研语言,AI、BlueOS 操作系统、团队成员聚集在北京,上海,南京,深圳,广州,宁夏等地。**
[/md]
欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/)
Powered by Discuz! X3.5