-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathfileUploadHandler.ts
More file actions
251 lines (216 loc) · 6.75 KB
/
fileUploadHandler.ts
File metadata and controls
251 lines (216 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import { randomBytes } from "node:crypto";
import { createReadStream, createWriteStream, statSync } from "node:fs";
import { rm, mkdir, stat as statAsync, unlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, extname, resolve as resolvePath } from "node:path";
import type { Readable } from "node:stream";
import { finished } from "node:stream";
import { promisify } from "node:util";
import { MaxPartSizeExceededError } from "@remix-run/server-runtime";
import type { UploadHandler } from "@remix-run/server-runtime";
// @ts-expect-error
import * as streamSlice from "stream-slice";
import {
createReadableStreamFromReadable,
readableStreamToString,
} from "../stream";
export type FileUploadHandlerFilterArgs = {
filename: string;
contentType: string;
name: string;
};
export type FileUploadHandlerPathResolverArgs = {
filename: string;
contentType: string;
name: string;
};
/**
* Chooses the path of the file to be uploaded. If a string is not
* returned the file will not be written.
*/
export type FileUploadHandlerPathResolver = (
args: FileUploadHandlerPathResolverArgs
) => string | undefined;
export type FileUploadHandlerOptions = {
/**
* Avoid file conflicts by appending a count on the end of the filename
* if it already exists on disk. Defaults to `true`.
*/
avoidFileConflicts?: boolean;
/**
* The directory to write the upload.
*/
directory?: string | FileUploadHandlerPathResolver;
/**
* The name of the file in the directory. Can be a relative path, the directory
* structure will be created if it does not exist.
*/
file?: FileUploadHandlerPathResolver;
/**
* The maximum upload size allowed. If the size is exceeded an error will be thrown.
* Defaults to 3000000B (3MB).
*/
maxPartSize?: number;
/**
*
* @param filename
* @param contentType
* @param name
*/
filter?(args: FileUploadHandlerFilterArgs): boolean | Promise<boolean>;
};
let defaultFilePathResolver: FileUploadHandlerPathResolver = ({ filename }) => {
let ext = filename ? extname(filename) : "";
return "upload_" + randomBytes(4).readUInt32LE(0) + ext;
};
async function uniqueFile(filepath: string) {
let ext = extname(filepath);
let uniqueFilepath = filepath;
for (
let i = 1;
await statAsync(uniqueFilepath)
.then(() => true)
.catch(() => false);
i++
) {
uniqueFilepath =
(ext ? filepath.slice(0, -ext.length) : filepath) +
`-${new Date().getTime()}${ext}`;
}
return uniqueFilepath;
}
export function createFileUploadHandler({
directory = tmpdir(),
avoidFileConflicts = true,
file = defaultFilePathResolver,
filter,
maxPartSize = 3000000,
}: FileUploadHandlerOptions = {}): UploadHandler {
return async ({ name, filename, contentType, data }) => {
if (
!filename ||
(filter && !(await filter({ name, filename, contentType })))
) {
return undefined;
}
let dir =
typeof directory === "string"
? directory
: directory({ name, filename, contentType });
if (!dir) {
return undefined;
}
let filedir = resolvePath(dir);
let path =
typeof file === "string" ? file : file({ name, filename, contentType });
if (!path) {
return undefined;
}
let filepath = resolvePath(filedir, path);
if (avoidFileConflicts) {
filepath = await uniqueFile(filepath);
}
await mkdir(dirname(filepath), { recursive: true }).catch(() => {});
let writeFileStream = createWriteStream(filepath);
let size = 0;
let deleteFile = false;
try {
for await (let chunk of data) {
size += chunk.byteLength;
if (size > maxPartSize) {
deleteFile = true;
throw new MaxPartSizeExceededError(name, maxPartSize);
}
writeFileStream.write(chunk);
}
} finally {
writeFileStream.end();
await promisify(finished)(writeFileStream);
if (deleteFile) {
await rm(filepath).catch(() => {});
}
}
// TODO: remove this typecast once TS fixed File class regression
// https://github.com/microsoft/TypeScript/issues/52166
return new NodeOnDiskFile(filepath, contentType) as unknown as File;
};
}
// TODO: remove this `Omit` usage once TS fixed File class regression
// https://github.com/microsoft/TypeScript/issues/52166
export class NodeOnDiskFile implements Omit<File, "constructor"> {
name: string;
lastModified: number = 0;
webkitRelativePath: string = "";
// TODO: remove this property once TS fixed File class regression
// https://github.com/microsoft/TypeScript/issues/52166
prototype = File.prototype;
constructor(
private filepath: string,
public type: string,
private slicer?: { start: number; end: number }
) {
this.name = basename(filepath);
}
get size(): number {
let stats = statSync(this.filepath);
if (this.slicer) {
let slice = this.slicer.end - this.slicer.start;
return slice < 0 ? 0 : slice > stats.size ? stats.size : slice;
}
return stats.size;
}
slice(start?: number, end?: number, type?: string): Blob {
if (typeof start === "number" && start < 0) start = this.size + start;
if (typeof end === "number" && end < 0) end = this.size + end;
let startOffset = this.slicer?.start || 0;
start = startOffset + (start || 0);
end = startOffset + (end || this.size);
return new NodeOnDiskFile(
this.filepath,
typeof type === "string" ? type : this.type,
{
start,
end,
}
// TODO: remove this typecast once TS fixed File class regression
// https://github.com/microsoft/TypeScript/issues/52166
) as unknown as Blob;
}
async arrayBuffer(): Promise<ArrayBuffer> {
let stream: Readable = createReadStream(this.filepath);
if (this.slicer) {
stream = stream.pipe(
streamSlice.slice(this.slicer.start, this.slicer.end)
);
}
return new Promise((resolve, reject) => {
let buf: any[] = [];
stream.on("data", (chunk) => buf.push(chunk));
stream.on("end", () => resolve(Buffer.concat(buf)));
stream.on("error", (err) => reject(err));
});
}
stream(): ReadableStream<any>;
stream(): NodeJS.ReadableStream;
stream(): ReadableStream<any> | NodeJS.ReadableStream {
let stream: Readable = createReadStream(this.filepath);
if (this.slicer) {
stream = stream.pipe(
streamSlice.slice(this.slicer.start, this.slicer.end)
);
}
return createReadableStreamFromReadable(stream);
}
async text(): Promise<string> {
return readableStreamToString(this.stream());
}
public get [Symbol.toStringTag]() {
return "File";
}
remove(): Promise<void> {
return unlink(this.filepath);
}
getFilePath(): string {
return this.filepath;
}
}