Simple and modern API for multipart requests from the browser. Monitor upload progress and cancel on demand.
- ✅ No dependencies;
- ✅ 100% TypeScript;
- ✅ Returns a promise (
async
/await
friendly); - ✅ Cancel an ongoing request;
- ✅ Monitor upoad progress;
- ✅ Wraps native browser API;
- ✅ Sandbox example with React & react-dropzone;
- ✅ Framework agnostic.
Checkout the CodeSandbox Demo (React
& react-dropzone
).
npm:
npm install modern-multi-part
Browser:
<!-- Creates a global function "ModernMultiPart.sendMultiPart" -->
<script
type="text/javascript"
src="https://unpkg.com/modern-multi-part/dist/index.js"
></script>
The library is packaged as a UMD module. To build it from code:
npm run package
// If you're using npm:
import { sendMultiPart } from "modern-multi-part";
// If you imported via script in HTML
const sendMultiPart = ModernMultiPart.sendMultiPart;
// Sample file - you would usually get that from a file input field
const file = new File(["foo"], "foo.txt", { type: "text/plain" });
// Returns a normal promise you can await.
// Monitor progress with the "onprogress" callback
const resultPromise = sendMultiPart(
"https://httpbin.org/post",
{ file, textField: "sample-text" },
{
onprogress: (pe: ProgressEvent) =>
console.log(Math.floor((pe.loaded / pe.total) * 100, "%"),
}
);
// The promise has additional "cancel" method
// Typically, this is used from a cancel button onClick callback
resultPromise.cancel() // <-- will cancel operation
resultPromise.then(result => {
// Prints server response - e.g. 200
console.log(result.httpStatus);
// Prints response text (e.g. JSON response)
console.log(result.responseText);
// Prints whether the operation was aborted/cancelled using the "cancel" method
console.log(result.aborted);
})
The library introduces a single function sendMultiPart
with the following params:
endpoint
- the URL where the form will be submitted;formPayload
- they payload as an object/record;options
- additional options documented below.
The supported options are:
Name | Type | Default | Sample Value |
---|---|---|---|
headers |
object / key value pairs | {} |
{Authorization: "Bearer secret-token"} |
onprogress |
ProgressEvent handler | null |
(e) => console.log(100 * e.loaded / e.total, "%) |
username |
string for server auth | null |
|
password |
string for server auth | null |
|
timeoutMillis |
number for connection timeout in milliseconds | null |
10000 |
Calling the function returns a CancelablePromise
, which is a normal promise
with an additional method cancel
. Calling cancel
will abort
an ongoing request.
If the multi-part request is successfull, the promise resolves with a result in the format:
{
httpStatus: number;
responseText: string;
aborted: boolean;
}