Skip to content

Commit

Permalink
feat: 表单支持多文件 (#80)
Browse files Browse the repository at this point in the history
* Update helpers.ts

* 增加测试用例

---------

Co-authored-by: Jay Fong <fjc0kb@gmail.com>
  • Loading branch information
YujiaCheng1996 and fjc0k committed Feb 8, 2023
1 parent c7f5a5a commit 51f477b
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/helpers.ts
Expand Up @@ -219,11 +219,14 @@ export function prepare(
})
Object.keys(fileData).forEach(key => {
const options = (requestData[key] as FileData).getOptions()
formData.append(
key,
fileData[key],
useNativeFormData ? options?.filename : (options as any),
)
const files = Array.isArray(fileData[key]) ? fileData[key] : [fileData[key]]
files.forEach((file: Blob) => {
formData.append(
key,
file,
useNativeFormData ? options?.filename : (options as any),
)
})
})
return formData as any
}
Expand Down
22 changes: 22 additions & 0 deletions tests/__snapshots__/helpers.test.ts.snap
Expand Up @@ -155,6 +155,28 @@ Object {
}
`;

exports[`prepare 文件处理: file-multiple 1`] = `
Array [
Array [
"file",
"text1",
],
Array [
"file",
"text2",
],
]
`;

exports[`prepare 文件处理: file-single 1`] = `
Array [
Array [
"file",
"text1",
],
]
`;

exports[`prepare 查询参数支持数组: brackets 1`] = `
Object {
"allData": Object {},
Expand Down
43 changes: 43 additions & 0 deletions tests/helpers.test.ts
Expand Up @@ -176,4 +176,47 @@ describe('prepare', () => {
),
).toMatchSnapshot('json')
})

test('文件处理', async () => {
const payload = prepare(
{ path: '/test' } as Partial<RequestConfig> as any,
{
file: new FileData(
new Blob(['1'], {
type: 'text1',
}),
),
},
)
const files: any[] = []
payload.getFormData().forEach((v, k) => {
files.push([k, v])
})
for (const file of files) {
file[1] = file[1] instanceof File ? file[1].type : file[1]
}
expect(files).toMatchSnapshot('file-single')

const payload2 = prepare(
{ path: '/test' } as Partial<RequestConfig> as any,
{
file: new FileData([
new Blob(['1'], {
type: 'text1',
}),
new Blob(['2'], {
type: 'text2',
}),
]),
},
)
const files2: any[] = []
payload2.getFormData().forEach((v, k) => {
files2.push([k, v])
})
for (const file of files2) {
file[1] = file[1] instanceof File ? file[1].type : file[1]
}
expect(files2).toMatchSnapshot('file-multiple')
})
})

0 comments on commit 51f477b

Please sign in to comment.