Skip to content

Commit e5ecce8

Browse files
committed
fix: use the File {webkitRelativePath} property if it exists and is set
1 parent 768d42c commit e5ecce8

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/file.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ describe('toFile()', () => {
2929
expect(fileWithPath.path).toBe(name);
3030
});
3131

32+
it('uses the File {webkitRelativePath} as {path} if it exists', () => {
33+
const path = 'test/test.json';
34+
const file = new File([], name);
35+
Object.defineProperty(file, 'webkitRelativePath', {
36+
value: path
37+
});
38+
const fileWithPath = toFileWithPath(file);
39+
expect(fileWithPath.path).toBe(path);
40+
});
41+
3242
it('sets the {type} from extension', () => {
3343
const types = Array.from(COMMON_MIME_TYPES.values());
3444
const files = Array.from(COMMON_MIME_TYPES.keys())

src/file.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,16 @@ export const COMMON_MIME_TYPES = new Map([
1717

1818
export function toFileWithPath(file: File, path?: string): FileWithPath {
1919
const f = withMimeType(file);
20+
const {webkitRelativePath} = file as FileWithWebkitPath;
2021
Object.defineProperty(f, 'path', {
21-
value: typeof path === 'string' ? path : file.name,
22+
value: typeof path === 'string'
23+
? path
24+
// If <input webkitdirectory> is set,
25+
// the File will have a {webkitRelativePath} property
26+
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
27+
: typeof webkitRelativePath === 'string' && webkitRelativePath.length > 0
28+
? webkitRelativePath
29+
: file.name,
2230
writable: false,
2331
configurable: false
2432
});
@@ -29,6 +37,9 @@ export interface FileWithPath extends File {
2937
readonly path?: string;
3038
}
3139

40+
interface FileWithWebkitPath extends File {
41+
readonly webkitRelativePath?: string;
42+
}
3243

3344
function withMimeType(file: File) {
3445
const {name} = file;

0 commit comments

Comments
 (0)