Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support concurrency limit #541

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ React.render(<Upload />, container);
|style | object | {}| root component inline style |
|className | string | - | root component className |
|disabled | boolean | false | whether disabled |
|component | "div"|"span" | "span"| wrap component name |
|component | "div"|"span" | "span"|
|action| string &#124; function(file): string &#124; Promise&lt;string&gt; | | form action url |
|method | string | post | request method |
|directory| boolean | false | support upload whole directory |
Expand All @@ -69,6 +69,7 @@ React.render(<Upload />, container);
|accept | string | | input accept attribute |
|capture | string | | input capture attribute |
|multiple | boolean | false | only support ie10+|
|concurrencyLimit | number | | asynchronously posts files with the concurrency limit |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concurrencyLimit 的默认值是多少?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

默认值是 undefined,即不使用 concurrencyLimit

|onStart | function| | start upload file |
|onError| function| | error callback |
|onSuccess | function | | success callback |
Expand Down
45 changes: 36 additions & 9 deletions src/AjaxUploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import attrAccept from './attr-accept';
import type {
BeforeUploadFileType,
RcFile,
RequestTask,
UploadProgressEvent,
UploadProps,
UploadRequestError,
} from './interface';
import defaultRequest from './request';
import traverseFileTree from './traverseFileTree';
import getUid from './uid';
import asyncPool from './asyncPool';

interface ParsedFileInfo {
origin: RcFile;
Expand All @@ -21,15 +23,24 @@ interface ParsedFileInfo {
parsedFile: RcFile;
}

class AjaxUploader extends Component<UploadProps> {
state = { uid: getUid() };
interface UploadState {
uid: string;
requestTasks: RequestTask[];
}

class AjaxUploader extends Component<UploadProps, UploadState> {
state = { uid: getUid(), requestTasks: [] as RequestTask[] };

reqs: any = {};

private fileInput: HTMLInputElement;

private _isMounted: boolean;

appendRequstTask = (task: RequestTask) => {
this.setState(pre => ({ ...pre, requestTasks: [...pre.requestTasks, task] }));
};

onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { accept, directory } = this.props;
const { files } = e.target;
Expand Down Expand Up @@ -111,17 +122,32 @@ class AjaxUploader extends Component<UploadProps> {
return this.processFile(file, originFiles);
});

const { onBatchStart, concurrencyLimit } = this.props;
// Batch upload files
Promise.all(postFiles).then(fileList => {
const { onBatchStart } = this.props;

onBatchStart?.(fileList.map(({ origin, parsedFile }) => ({ file: origin, parsedFile })));

fileList
.filter(file => file.parsedFile !== null)
.forEach(file => {
const parsedFiles = fileList.filter(file => file.parsedFile !== null);
if (concurrencyLimit) {
// Asynchronously posts files with the concurrency limit.
asyncPool(
concurrencyLimit,
this.state.requestTasks,
item =>
new Promise<void>(resolve => {
const xhr = item.xhr;

item.done = resolve;

xhr.send(item.data);
}),
);
} else {
parsedFiles.forEach(file => {
this.post(file);
});
this.state.requestTasks.forEach(({ xhr, data }) => xhr.send(data));
}
});
};

Expand Down Expand Up @@ -162,7 +188,7 @@ class AjaxUploader extends Component<UploadProps> {
const { data } = this.props;
let mergedData: Record<string, unknown>;
if (typeof data === 'function') {
mergedData = await data(file);
mergedData = data(file);
} else {
mergedData = data;
}
Expand Down Expand Up @@ -230,12 +256,13 @@ class AjaxUploader extends Component<UploadProps> {
};

onStart(origin);
this.reqs[uid] = request(requestOption);
this.reqs[uid] = request(requestOption, this.appendRequstTask);
}

reset() {
this.setState({
uid: getUid(),
requestTasks: [],
});
}

Expand Down
38 changes: 38 additions & 0 deletions src/asyncPool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Asynchronously processes an array of items with a concurrency limit.
*
* @template T - Type of the input items.
* @template U - Type of the result of the asynchronous task.
*
* @param {number} concurrencyLimit - The maximum number of asynchronous tasks to execute concurrently.
* @param {T[]} items - The array of items to process asynchronously.
* @param {(item: T) => Promise<U>} asyncTask - The asynchronous task to be performed on each item.
*
* @returns {Promise<U[]>} - A promise that resolves to an array of results from the asynchronous tasks.
*/
export default async function asyncPool<T, U>(
concurrencyLimit: number,
items: T[],
asyncTask: (item: T) => Promise<U>,
): Promise<U[]> {
const tasks: Promise<U>[] = [];
const pendings: Promise<U>[] = [];

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

多了一个空行。

for (const item of items) {
const task = asyncTask(item);
tasks.push(task);

if (concurrencyLimit <= items.length) {
task.then(() => {
pendings.splice(pendings.indexOf(task), 1);
});
pendings.push(task);

if (pendings.length >= concurrencyLimit) {
await Promise.race(pendings);
}
}
}

return Promise.all(tasks);
}
9 changes: 8 additions & 1 deletion src/interface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export interface UploadProps
file: RcFile,
FileList: RcFile[],
) => BeforeUploadFileType | Promise<void | BeforeUploadFileType> | void;
customRequest?: (option: UploadRequestOption) => void;
customRequest?: (option: UploadRequestOption) => void | { abort: () => void };
withCredentials?: boolean;
openFileDialogOnClick?: boolean;
prefixCls?: string;
Expand All @@ -44,6 +44,7 @@ export interface UploadProps
input?: React.CSSProperties;
};
hasControlInside?: boolean;
concurrencyLimit?: number;
}

export interface UploadProgressEvent extends Partial<ProgressEvent> {
Expand Down Expand Up @@ -76,3 +77,9 @@ export interface UploadRequestOption<T = any> {
export interface RcFile extends File {
uid: string;
}

export interface RequestTask {
xhr: XMLHttpRequest;
data: File | FormData;
done?: () => void;
}
19 changes: 16 additions & 3 deletions src/request.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { UploadRequestOption, UploadRequestError, UploadProgressEvent } from './interface';
import type {
UploadRequestOption,
UploadRequestError,
UploadProgressEvent,
RequestTask,
} from './interface';

function getError(option: UploadRequestOption, xhr: XMLHttpRequest) {
const msg = `cannot ${option.method} ${option.action} ${xhr.status}'`;
Expand All @@ -22,7 +27,10 @@ function getBody(xhr: XMLHttpRequest) {
}
}

export default function upload(option: UploadRequestOption) {
export default function upload(
option: UploadRequestOption,
appendTask: (task: RequestTask) => void,
) {
// eslint-disable-next-line no-undef
const xhr = new XMLHttpRequest();

Expand Down Expand Up @@ -62,11 +70,16 @@ export default function upload(option: UploadRequestOption) {
formData.append(option.filename, option.file);
}

const task: RequestTask = { xhr, data: formData };

xhr.onerror = function error(e) {
option.onError(e);
task.done?.();
};

xhr.onload = function onload() {
task.done?.();

// allow success when 2xx status
// see https://github.com/react-component/upload/issues/34
if (xhr.status < 200 || xhr.status >= 300) {
Expand Down Expand Up @@ -97,7 +110,7 @@ export default function upload(option: UploadRequestOption) {
}
});

xhr.send(formData);
appendTask(task);

return {
abort() {
Expand Down
Loading