跳转到内容

文件下载

下载文件到本地存储。

const cancel = SuperSDK.downloadFile({
url: 'https://example.com/file.zip',
savePath: 'downloads/file.zip',
headers: {
'Authorization': 'Bearer token123'
},
onStart: () => {
console.log('开始下载');
},
onProgress: ({ progress, downloadedBytes, totalBytes }) => {
console.log(`下载进度: ${progress}%`);
},
onSuccess: ({ filePath, downloadedBytes, totalBytes }) => {
console.log('下载完成:', filePath);
},
onFail: ({ error }) => {
console.error('下载失败:', error);
}
});
// 取消下载
cancel();

参数说明:

参数类型必填说明
urlstring是文件下载地址
savePathstring是保存路径(相对于 SDK 文件存储目录)
headersobject否请求头
onStartfunction否开始下载回调
onProgressfunction否进度回调,约 300ms 触发一次
onSuccessfunction否成功回调
onFailfunction否失败回调

onProgress 回调参数:

参数类型说明
progressnumber下载进度 0-100
downloadedBytesnumber已下载字节数
totalBytesnumber文件总字节数

onSuccess 回调参数:

参数类型说明
filePathstring文件绝对路径
downloadedBytesnumber已下载字节数
totalBytesnumber文件总字节数

onFail 回调参数:

参数类型说明
errorstring错误信息

downloadWithCache(fileUrl, fileMd5, cacheTts, fileCacheKey)

Section titled “downloadWithCache(fileUrl, fileMd5, cacheTts, fileCacheKey)”

下载文件并写入 SDK 缓存目录。缓存命中时不会重新下载,直接返回本地文件路径。

const result = await SuperSDK.downloadWithCache(
'https://example.com/assets/file.zip?token=abc',
'd41d8cd98f00b204e9800998ecf8427e',
86400,
'asset-file-v1'
);
console.log(result);
// { filePath: '/path/to/download_cache/xxx.zip', cacheHit: true, cacheKey: 'asset-file-v1' }

参数说明:

参数类型必填说明
fileUrlstring是文件下载地址
fileMd5string否文件 MD5;为空时跳过 MD5 校验
cacheTtsnumber否缓存有效期,单位秒;<= 0 时强制重新下载
fileCacheKeystring否自定义缓存 key;为空或不传时使用去掉 query 的 fileUrl

缓存规则:

  • 缓存 key 优先使用非空 fileCacheKey,否则使用去掉 query 的 fileUrl。
  • Native 会把缓存 key 转成安全文件名,不直接拼接 URL 到文件路径。
  • fileMd5 非空时会校验缓存文件和新下载文件;新下载文件 MD5 不匹配时失败,且不会覆盖旧缓存。

返回值:

参数类型说明
filePathstring本地缓存文件绝对路径
cacheHitboolean是否命中缓存
cacheKeystring本次实际使用的原始缓存 key