0.0.4 • Published 2 years ago

modern-multi-part v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Modern Multi Part

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).

Installation

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

Annotated Code Example

// 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);
})

API

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:

NameTypeDefaultSample Value
headersobject / key value pairs{}{Authorization: "Bearer secret-token"}
onprogressProgressEvent handlernull(e) => console.log(100 * e.loaded / e.total, "%)
usernamestring for server authnull
passwordstring for server authnull
timeoutMillisnumber for connection timeout in millisecondsnull10000

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;
}