Skip to content

下载文件 ​

下载文件资源到本地,客户端直接发起一个 downloadFile 请求,返回文件的本地临时路径。

请求参数 ​

值类型必备默认值描述
urlstring是-开发者服务器接口地址
headerUTSJSONObject否nullHTTP 请求 Header, header 中不能设置 Referer
filePathstring否null要上传文件资源的路径, 支持uni.env
downloadFileTimeoutnumber否120000超时时间,单位 ms
closeInterceptorboolean否false关闭当前请求的拦截器
success(res: UTSJSONObject) => void否null成功返回的回调函数
fail(fail: UTSJSONObject) => void否null失败的回调函数
complete(all: UTSJSONObject) => void否null结束的回调函数(调用成功、失败都会执行),成功或者失败都会调用。
downloadTask(task : DownloadTask) => void否-UploadTask 的方法

success返回值 ​

值类型必备默认值描述兼容性
tempFilePathstring是-临时文件路径,下载后的文件会存储到一个临时文件
statusCodenumber是-开发者服务器返回的 HTTP 状态码
filePathstring否-用户文件路径 (本地路径)。传入 filePath 时会返回,跟传入的 filePath 一致微信小程序

fail返回值 ​

值类型必备默认值描述兼容性
errCodenumber是-错误码
errSubjectstring是-统一错误主题(模块)名称
dataany否-错误信息中包含的数据微信小程序
causeError否-源错误信息,可以包含多个错误,详见SourceError
errMsgstring是-

errCode合法值 ​

值描述
5接口超时
1000服务端系统错误
100001json数据解析错误
100002错误信息json解析失败
100003json解析类型转换失败
600003网络中断
600008data参数类型不合法
600009URL格式不合法
602001request系统错误

注意事项 ​

  • 当目录下有同名文件时,文件名会增加数字后缀,例如:目录下abc.txt已经存在,此时下载此文件名的文件到此目录时,下载后的文件会命名为abc(1).txt。
  • App-Android下载的默认目录为外置应用沙盒目录下的cache目录。如果手机磁盘空间不足,系统清理工具会清理cache目录。
  • 如需主动删除下载文件,使用uni.getFileSystemManager。
  • 默认下载路径为外置应用沙盒目录uni.env.CACHE_PATH/cache/uni-download。但在HBuilderX 3.99前有过几次变更,3.98的目录是uni.env.CACHE_PATH/cache/uniDownloads,而3.98之前则不在cache目录下。

downloadFile 请求示例 ​

ts
<script setup>
	import { http } from "@/uni_modules/ucs-request";
	
	http.downloadFile({
		url: "api/xxxxxx/xxxxxx",
		success: (res) => {
			console.log(res)
		},
		fail: (fail) => {
			console.log(fail)
		},
		complete: (e) => {
			console.log(e)
		}
	})
</script>

DownloadTask 方法 ​

abort(): void ​

abort 中断下载任务

onProgressUpdate(callback: DownloadFileProgressUpdateCallback): void ​

onProgressUpdate 监听下载进度变化

值类型必备默认值描述兼容性
callback(result: OnProgressDownloadResult) => void是--

OnProgressDownloadResult属性值 ​

值类型必备默认值描述兼容性
progressnumber是-下载进度百分比
totalBytesWrittennumber是-已经下载的数据长度,单位 Bytes
totalBytesExpectedToWritenumber是-预期需要下载的数据总长度,单位 Bytes

DownloadTask 示例 ​

ts
<script setup>
	import { http } from "@/uni_modules/ucs-request";
	
	http.downloadFile({
		url: "api/xxxxxx/xxxxxx",
		downloadTask: (task : DownloadTask) => {
			// 方法调用
			task.onProgressUpdate((taskRes) => {
				console.log('下载进度:', taskRes.progress)
			})
		},
		success: (res) => {
			console.log(res)
		},
		fail: (fail) => {
			console.log(fail)
		},
		complete: (e) => {
			console.log(e)
		}
	})
</script>