Skip to content

Commit b598745

Browse files
authored
feat(h5): 支持 saveFileToDisk (#19670)
* feat(h5): support saving files to disk * fix(harmony-hybrid): keep saveFileToDisk unsupported * fix(harmony-hybrid): export saveFileToDisk once * test(h5): run Hybrid export checks after explicit builds
1 parent 3532ac9 commit b598745

7 files changed

Lines changed: 119 additions & 15 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { saveFileToDisk } from '@tarojs/taro-h5'
2+
3+
describe('saveFileToDisk', () => {
4+
afterEach(() => jest.restoreAllMocks())
5+
6+
it.each(['/reports/monthly.csv', 'blob:http://localhost/recording'])('requests a browser download for %s', async filePath => {
7+
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
8+
const success = jest.fn()
9+
const complete = jest.fn()
10+
const result = await saveFileToDisk({ filePath, success, complete })
11+
const link = click.mock.instances[0] as HTMLAnchorElement
12+
13+
expect(link.href).toBe(new URL(filePath, document.baseURI).href)
14+
expect(link.hasAttribute('download')).toBe(true)
15+
expect(result.errMsg).toBe('saveFileToDisk:ok')
16+
expect(success).toHaveBeenCalledWith(result)
17+
expect(complete).toHaveBeenCalledWith(result)
18+
})
19+
20+
it.each(['', 'javascript:void(0)', 'https://example.com/report.csv'])('fails without opening %s', async filePath => {
21+
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
22+
await expect(saveFileToDisk({ filePath })).rejects.toMatchObject({
23+
errMsg: expect.stringContaining('saveFileToDisk:fail'),
24+
})
25+
expect(click).not.toHaveBeenCalled()
26+
})
27+
})
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { isAbsolute, resolve } from 'node:path'
2+
import { runInNewContext } from 'node:vm'
3+
4+
import Taro from '@tarojs/api'
5+
import { rollup } from 'rollup'
6+
7+
const publicApi = resolve(__dirname, '../../../taro-platform-harmony-hybrid/dist/api/index.js')
8+
const consumer = '\0save-file-to-disk-consumer'
9+
10+
afterEach(() => jest.restoreAllMocks())
11+
12+
it('reports saveFileToDisk as unsupported in Harmony Hybrid without requesting a download', async () => {
13+
jest.replaceProperty(process.env, 'NODE_ENV', 'production')
14+
jest.spyOn(console, 'warn').mockImplementation(() => {})
15+
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
16+
const unsupported = jest.fn()
17+
const options = { filePath: '/reports/monthly.csv' }
18+
19+
// Bundle a named import from the same generated entry that apps consume.
20+
const bundle = await rollup({
21+
input: consumer,
22+
external: (id, importer) => !!importer && !id.startsWith('.') && !isAbsolute(id),
23+
treeshake: { moduleSideEffects: false },
24+
plugins: [{
25+
name: 'save-file-to-disk-consumer',
26+
resolveId: id => id === consumer ? id : null,
27+
load: id => id === consumer ? `export { saveFileToDisk } from ${JSON.stringify(publicApi)}` : null,
28+
}],
29+
})
30+
const exports: Pick<typeof Taro, 'saveFileToDisk'> = Object.create(null)
31+
try {
32+
const { output } = await bundle.generate({ format: 'cjs', exports: 'named', interop: 'auto' })
33+
runInNewContext(output[0].code, { exports, require, process, console, document, window })
34+
} finally {
35+
await bundle.close()
36+
}
37+
38+
Taro.eventCenter.on('__taroNotSupport', unsupported)
39+
try {
40+
await expect(exports.saveFileToDisk(options)).resolves.toEqual({ errMsg: '暂时不支持 API' })
41+
expect(unsupported).toHaveBeenCalledWith({
42+
name: 'saveFileToDisk',
43+
args: [options],
44+
type: 'method',
45+
category: 'temporarily',
46+
})
47+
expect(click).not.toHaveBeenCalled()
48+
} finally {
49+
Taro.eventCenter.off('__taroNotSupport', unsupported)
50+
}
51+
})

‎packages/taro-h5/src/api/files/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { temporarilyNotSupport } from '../../utils'
22

33
// 文件
4-
export const saveFileToDisk = /* @__PURE__ */ temporarilyNotSupport('saveFileToDisk')
4+
export * from './saveFileToDisk'
55
export const saveFile = /* @__PURE__ */ temporarilyNotSupport('saveFile')
66
export const removeSavedFile = /* @__PURE__ */ temporarilyNotSupport('removeSavedFile')
77
export const openDocument = /* @__PURE__ */ temporarilyNotSupport('openDocument')
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import Taro from '@tarojs/api'
2+
3+
import { createDownload, shouldBeObject } from '../../utils'
4+
import { MethodHandler } from '../../utils/handler'
5+
6+
export const saveFileToDisk: typeof Taro.saveFileToDisk = async options => {
7+
const name = 'saveFileToDisk'
8+
const validation = shouldBeObject(options)
9+
if (!validation.flag) return new MethodHandler({ name }).fail({ errMsg: validation.msg })
10+
11+
const { filePath, success, fail, complete } = options
12+
const handler = new MethodHandler({ name, success, fail, complete })
13+
if (typeof filePath !== 'string' || !filePath.trim()) {
14+
return handler.fail({ errMsg: 'filePath must be a non-empty string' })
15+
}
16+
17+
try {
18+
const url = new URL(filePath, document.baseURI)
19+
if (url.protocol !== 'blob:' &&
20+
((url.protocol !== 'http:' && url.protocol !== 'https:') || url.origin !== window.location.origin)) {
21+
throw new Error('filePath must be a same-origin HTTP(S) URL or a Blob URL')
22+
}
23+
createDownload(url.href)
24+
} catch (error) {
25+
return handler.fail({ errMsg: error instanceof Error ? error.message : String(error) })
26+
}
27+
return handler.success()
28+
}

‎packages/taro-platform-harmony-hybrid/src/api/apis/comments.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,12 +1284,6 @@
12841284
* @canNotUse reserveChannelsLive
12851285
*/
12861286

1287-
/**
1288-
* 保存文件系统的文件到用户磁盘,仅在 PC 端支持
1289-
*
1290-
* @canNotUse saveFileToDisk
1291-
*/
1292-
12931287
/**
12941288
* 控制音乐播放进度
12951289
*

‎packages/taro-platform-harmony-hybrid/src/api/apis/files/index.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1-
/**
2-
* 保存文件系统的文件到用户磁盘,仅在 PC 端支持
3-
*
4-
* @canNotUse saveFileToDisk
5-
*/
1+
import { temporarilyNotSupport } from '../utils'
2+
63
export * from './getFileInfo'
74
export * from './getFileSystemManager'
85
export * from './getSavedFileInfo'
96
export * from './getSavedFileList'
107
export * from './openDocument'
118
export * from './removeSavedFile'
129
export * from './saveFile'
13-
export { saveFileToDisk } from '@tarojs/taro-h5'
10+
11+
/**
12+
* 保存文件系统的文件到用户磁盘,仅在 PC 端支持
13+
*
14+
* @canNotUse saveFileToDisk
15+
*/
16+
export const saveFileToDisk = /* @__PURE__ */ temporarilyNotSupport('saveFileToDisk')
1417

1518
/**
1619
* 描述文件状态的对象

‎packages/taro/types/api/files/index.d.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,8 +1337,9 @@ declare module '../../index' {
13371337
}
13381338

13391339
interface TaroStatic {
1340-
/** 保存文件系统的文件到用户磁盘,仅在 PC 端支持
1341-
* @supported weapp, alipay
1340+
/** 保存文件到用户磁盘。小程序端仅在 PC 上支持。
1341+
* H5 接受同源文件地址和 Blob URL,成功回调表示已请求浏览器下载。
1342+
* @supported weapp, alipay, h5
13421343
* @example
13431344
* ```tsx
13441345
* Taro.saveFileToDisk({

0 commit comments

Comments
 (0)