Skip to content

下载文件

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

请求参数

类型必备默认值描述
urlstring-开发者服务器接口地址
headerUTSJSONObjectnullHTTP 请求 Header, header 中不能设置 Referer
filePathstringnull要上传文件资源的路径, 支持uni.env
downloadFileTimeoutnumber120000超时时间,单位 ms
closeInterceptorbooleanfalse关闭当前请求的拦截器
success(res: UTSJSONObject) => voidnull成功返回的回调函数
fail(fail: UTSJSONObject) => voidnull失败的回调函数
complete(all: UTSJSONObject) => voidnull结束的回调函数(调用成功、失败都会执行),成功或者失败都会调用。
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>
	// 1、引入自定义创建实例
	import request from "@/xxxxxx/xxxxxx";
	// 2、基础使用
	request.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>
	// 1、引入自定义创建实例
	import request from "@/xxxxxx/xxxxxx";
	// 2、基础使用
	request.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>