### Install and Start React Native Demo Source: https://github.com/tus/tus-js-client/blob/main/demos/reactnative/README.md Run these commands in the demo directory to install dependencies and start the Expo development server. ```bash npm install npm start ``` -------------------------------- ### Install tus-js-client using NPM Source: https://github.com/tus/tus-js-client/blob/main/docs/installation.md Install the tus-js-client package using npm or yarn. This is the recommended installation method. ```bash $ npm install --save tus-js-client ``` -------------------------------- ### tus.Upload Constructor Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Initializes a new tus.Upload instance. The upload process is not started automatically and requires calling the `start` method. ```APIDOC ## tus.Upload(file, options) The constructor for the `tus.Upload` class. The upload will not be started automatically, use `start` to do so. Depending on the platform, the `file` argument must be an instance of the following types: - inside browser: `File`, `Blob`, or [`Reader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) - inside Node.js: `Buffer` or `Readable` stream - inside Cordova: `File` object from a `FileEntry` (see [demo](/demos/cordova/www/js/index.js)) - inside React Native: Object with uri property: `{ uri: 'file:///...', ... }` (see [installation notes](/docs/installation.md#react-native-support) and [demo](/demos/reactnative/App.js)) The `options` argument will be merged deeply with `tus.defaultOptions`. See its documentation for more details. If you pass a `Reader` or `Readable` stream, tus-js-client will take care of closing/cancelling the stream once the upload is complete (i.e. the `onSuccess` callback is invoked). It will not close the stream if you stop the upload prematurely using `abort()` or if an error occurs (`onError` callback) because you might want to resume the upload. If you do not want to continue the upload, you must close/cancel the stream on your own. ``` -------------------------------- ### tus.Upload#resumeFromPreviousUpload(previousUpload) Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Configures the upload instance to resume using the upload URL specified in the `previousUpload` object. The `previousUpload` object must be in the format returned by the `tus.Upload#findPreviousUploads` method. Further details and an example are available in the Usage Guide. ```APIDOC ## tus.Upload#resumeFromPreviousUpload(previousUpload) Configure the upload instance to resume using the upload URL as specified in `previousUpload`. The value in `previousUpload` must be an object as returned from the `tus.Upload#findPreviousUploads` method. An example and more details on how to use this function can be found in the [Usage Guide](/docs/usage.md#example-let-user-select-upload-to-resume). ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Clone the tus-js-client repository and install project dependencies using Yarn. ```bash git clone git@github.com:tus/tus-js-client.git cd tus-js-client yarn install ``` -------------------------------- ### tus.Upload#start() Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Starts or resumes an upload using the specified file. If no `file` property is available, the error handler will be called. If an `uploadUrl` option was provided, the client will attempt to resume using that URL. Alternatively, `tus.Upload#findPreviousUploads` and `tus.Upload#resumeFromPreviousUpload` can be used to query for previous uploads. If no upload can be resumed, a new upload will be created using the `endpoint` option. ```APIDOC ## tus.Upload#start() Start or resume the upload using the specified file. If no `file` property is available the error handler will be called. If you supplied your own URL using the `uploadUrl` option the client will try to resume using this URL. Alternatively, you can use `tus.Upload#findPreviousUploads` and `tus.Upload#resumeFromPreviousUpload` to query the URL storage for previous uploads for this specific file. If no upload can be resume it will create a new upload using the supplied `endpoint` option. ``` -------------------------------- ### Create and Start Tus Upload Source: https://github.com/tus/tus-js-client/blob/main/README.md Handles file selection from an input element, creates a new tus upload, and resumes from previous uploads if available before starting. ```javascript input.addEventListener('change', function (e) { // Get the selected file from the input element var file = e.target.files[0] // Create a new tus upload var upload = new tus.Upload(file, { endpoint: 'http://localhost:1080/files/', retryDelays: [0, 3000, 5000, 10000, 20000], metadata: { filename: file.name, filetype: file.type, }, onError: function (error) { console.log('Failed because: ' + error) }, onProgress: function (bytesUploaded, bytesTotal) { var percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2) console.log(bytesUploaded, bytesTotal, percentage + '%') }, onSuccess: function () { console.log('Download %s from %s', upload.file.name, upload.url) }, }) // Check if there are any previous uploads to continue. upload.findPreviousUploads().then(function (previousUploads) { // Found previous uploads so we select the first one. if (previousUploads.length) { upload.resumeFromPreviousUpload(previousUploads[0]) } // Start the upload upload.start() }) }) ``` -------------------------------- ### Load tus-js-client with CommonJS Source: https://github.com/tus/tus-js-client/blob/main/docs/installation.md Load the tus-js-client library after installation using require. This is common in Node.js or older bundler setups. ```javascript var tus = require('tus-js-client') ``` -------------------------------- ### tus.Upload#findPreviousUploads() Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Queries the URL storage using the input file's fingerprint to retrieve a list of previously started uploads for that file. To resume an upload, pass the corresponding object to `tus.Upload#resumeFromPreviousUpload` before calling `tus.Upload#start`. Returns a Promise that resolves to a list of `PreviousUpload` objects. ```APIDOC ## tus.Upload#findPreviousUploads() Query the URL storage using the input file's fingerprint to retrieve a list of uploads for the input file, which have previously been started by the user. If you want to resume one of these uploads, pass the corresponding object to `tus.Upload#resumeFromPreviousUpload` before calling `tus.Upload#start`. The function returns a `Promise`, which resolves to a list with following structure: ```typescript findPreviousUploads(): Promise>; interface PreviousUpload { size: number | null; metadata: object; creationTime: string; urlStorageKey: string; uploadUrl: string | null; parallelUploadUrls: string[] | null; } ``` An example and more details on how to use this function can be found in the [Usage Guide](/docs/usage.md#example-let-user-select-upload-to-resume). ``` -------------------------------- ### Polyfill Promises and Load tus-js-client Source: https://github.com/tus/tus-js-client/blob/main/docs/installation.md When running in environments without native Promise support, load a Promise polyfill before tus-js-client. This example uses core-js. ```javascript require('core-js/features/promise') var tus = require('tus-js-client') ``` -------------------------------- ### Configure Parallel Upload Boundaries Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Specify custom boundaries for parallel uploads. The array length must match `parallelUploads`. Each object requires `start` and `end` properties. If null, the upload is split equally. ```javascript parallelUploadBoundaries: [{ start: 0, end: 1 }, { start: 1, end: 11 }], ``` -------------------------------- ### Pauseable Upload with tus-js-client Source: https://github.com/tus/tus-js-client/blob/main/docs/usage.md Illustrates how to implement a pauseable upload using tus-js-client, allowing users to pause and unpause uploads via buttons. It includes the necessary setup for creating an upload, handling its lifecycle, and attaching event listeners to control the upload state. ```javascript // Obtain file from user input or similar var file = ... function startOrResumeUpload(upload) { // Check if there are any previous uploads to continue. upload.findPreviousUploads().then(function (previousUploads) { // Found previous uploads so we select the first one. if (previousUploads.length) { upload.resumeFromPreviousUpload(previousUploads[0]) } // Start the upload upload.start() }) } // Create the tus upload similar to the example from above var upload = new tus.Upload(file, { endpoint: "http://localhost:1080/files/", onError: function(error) { console.log("Failed because: " + error) }, onSuccess: function() { console.log("Download %s from %s", upload.file.name, upload.url) } }) // Add listeners for the pause and unpause button var pauseButton = document.querySelector("#pauseButton") var unpauseButton = document.querySelector("#unpauseButton") pauseButton.addEventListener("click", function() { upload.abort() }) unpauseButton.addEventListener("click", function() { startOrResumeUpload(upload) }) // Start the upload by default startOrResumeUpload(upload) ``` -------------------------------- ### Resume Upload Across Browser Sessions Source: https://github.com/tus/tus-js-client/blob/main/docs/usage.md Query URL storage to find previously started uploads for a file and prompt the user to resume. This enables resumability even after browser restarts. ```javascript var file = ... var options = ... var upload = new tus.Upload(file, options) // Retrieve a list of uploads that have been previously started for this file. // These uploads will be queried from the URL Storage using the file's fingerprint. upload.findPreviousUploads().then((previousUploads) => { // previousUploads is an array containing details about the previously started uploads. // The objects in the array have following properties: // - size: The upload's size in bytes // - metadata: The metadata associated with the upload during its creation // - creationTime: The timestamp when the upload was created // We ask the end user if they want to resume one of those uploads or start a new one. var chosenUpload = askToResumeUpload(previousUploads); // If an upload has been chosen to be resumed, instruct the upload object to do so. if(chosenUpload) { upload.resumeFromPreviousUpload(chosenUpload); } // Finally start the upload requests. upload.start(); }); // Open a dialog box to the user where they can select whether they want to resume an upload // or instead create a new one. function askToResumeUpload(previousUploads) { if (previousUploads.length === 0) return null; var text = "You tried to upload this file previously at these times:\n\n"; previousUploads.forEach((previousUpload, index) => { text += "[" + index + "] " + previousUpload.creationTime + "\n"; }); text += "\nEnter the corresponding number to resume an upload or press Cancel to start a new upload"; var answer = prompt(text); var index = parseInt(answer, 10); if (!isNaN(index) && previousUploads[index]) { return previousUploads[index]; } } ``` -------------------------------- ### Configure Retry Delays for Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Set custom delays in milliseconds for upload retries after an interruption. The array length determines the maximum number of attempts. This example configures up to three retries with specific delays. ```javascript retryDelays: [1000, 3000, 5000] ``` -------------------------------- ### Find Previous Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Query the URL storage to retrieve a list of previously started uploads for a given file fingerprint. The returned promise resolves to an array of `PreviousUpload` objects, each containing details like size, metadata, and upload URLs. ```typescript findPreviousUploads(): Promise>; interface PreviousUpload { size: number | null; metadata: object; creationTime: string; urlStorageKey: string; uploadUrl: string | null; parallelUploadUrls: string[] | null; } ``` -------------------------------- ### Override Retry Behavior on 403 Status Source: https://github.com/tus/tus-js-client/blob/main/docs/usage.md Customize the retry logic by providing an `onShouldRetry` callback. This example prevents retries for a 403 status code, logging the error directly. ```javascript input.addEventListener('change', function (e) { // Get the selected file from the input element var file = e.target.files[0] // Create a new tus upload var upload = new tus.Upload(file, { endpoint: 'http://localhost:1080/files/', retryDelays: [0, 3000, 5000, 10000, 20000], metadata: { filename: file.name, filetype: file.type, }, onError: function (error) { // Display an error message console.log('Failed because: ' + error) }, onShouldRetry: function (err, retryAttempt, options) { var status = err.originalResponse ? err.originalResponse.getStatus() : 0 // If the status is a 403, we do not want to retry. if (status === 403) { return false } // For any other status code, tus-js-client should retry. return true }, }) // Check if there are any previous uploads to continue. upload.findPreviousUploads().then(function (previousUploads) { // Found previous uploads so we select the first one. if (previousUploads.length) { upload.resumeFromPreviousUpload(previousUploads[0]) } // Start the upload upload.start() }) }) ``` -------------------------------- ### parallelUploadBoundaries Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An array indicating the boundaries of different parts uploaded during a parallel upload. This option is only considered if `parallelUploads` is greater than 1. The length of `parallelUploadBoundaries` must match `parallelUploads`. Each element must have `start` and `end` properties. ```APIDOC ## parallelUploadBoundaries ### Description An array indicating the boundaries of the different parts uploaded during a parallel upload. This option is only considered if `parallelUploads` is greater than `1`. If so, the length of `parallelUploadBoundaries` must match `parallelUploads`. Each element in this array must have a `start` and `end` property indicating the start and end position of the partial upload. ### Example ```javascript parallelUploadBoundaries: [{ start: 0, end: 1 }, { start: 1, end: 11 }] ``` It is the user's responsibility to ensure that the boundaries are consecutive and occupy the entire file size. If `parallelUploadBoundaries` is `null` (default value), the upload will be split into roughly equally sized parts. ``` -------------------------------- ### Build and Watch Project Files Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Build the library bundle and all test scripts, or watch source files for changes and automatically rebuild. ```bash yarn run build ``` ```bash yarn run watch ``` -------------------------------- ### Execute Cordova Demo Source: https://github.com/tus/tus-js-client/blob/main/demos/cordova/README.md Run this command in the project root to build and deploy the Cordova demo application to an Android device or emulator. ```sh cordova run android ``` -------------------------------- ### Build tus-js-client for Cordova Demo Source: https://github.com/tus/tus-js-client/blob/main/demos/cordova/README.md Run this command in the project root to build the tus-js-client files before executing the Cordova demo. ```sh cd ../.. npm run dist ``` -------------------------------- ### Simple File Upload with tus-js-client Source: https://github.com/tus/tus-js-client/blob/main/docs/usage.md Demonstrates the most basic usage of tus-js-client for uploading a single file. It includes configuration for the endpoint, retry delays, metadata, and callbacks for error handling, progress reporting, and success notifications. It also shows how to find and resume previous uploads. ```javascript input.addEventListener('change', function (e) { // Get the selected file from the input element var file = e.target.files[0] // Create a new tus upload var upload = new tus.Upload(file, { // Endpoint is the upload creation URL from your tus server endpoint: 'http://localhost:1080/files/', // Retry delays will enable tus-js-client to automatically retry on errors retryDelays: [0, 3000, 5000, 10000, 20000], // Attach additional meta data about the file for the server metadata: { filename: file.name, filetype: file.type, }, // Callback for errors which cannot be fixed using retries onError: function (error) { console.log('Failed because: ' + error) }, // Callback for reporting upload progress onProgress: function (bytesUploaded, bytesTotal) { var percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2) console.log(bytesUploaded, bytesTotal, percentage + '%') }, // Callback for once the upload is completed onSuccess: function () { console.log('Download %s from %s', upload.file.name, upload.url) }, }) // Check if there are any previous uploads to continue. upload.findPreviousUploads().then(function (previousUploads) { // Found previous uploads so we select the first one. if (previousUploads.length) { upload.resumeFromPreviousUpload(previousUploads[0]) } // Start the upload upload.start() }) }) ``` -------------------------------- ### Manage Project Versioning Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Update the project version using npm and push the changes, or directly edit `package.json` for releases. Supports pre-releases with suffixes. ```bash npm version ``` -------------------------------- ### Add Request ID Header Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Enable adding a UUID v4 request ID to HTTP headers for error correlation. Ensure your CORS setup allows the 'X-Request-ID' header. ```text X-Request-ID: fe51f777-f23e-4ed9-97d7-2785cc69f961 ``` -------------------------------- ### View Tests in Browser Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Open the `SpecRunner.html` file in a browser to view test results visually. No web server is required. ```html file:///path/to/your/tus-js-client/test/SpecRunner.html ``` -------------------------------- ### Configure Upload Endpoint Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Set the upload creation URL for new uploads. This is a fundamental option for initiating file transfers. ```javascript endpoint: 'http://tusd.tusdemo.net/files/' ``` -------------------------------- ### Run Tests in Node.js Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Execute the project tests within the Node.js environment. ```bash yarn run test-node ``` -------------------------------- ### tus.Upload#abort(shouldTerminate) Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Aborts the currently running upload request without continuing. The upload can be resumed by calling the `start` method again. This method does not release the provided file, allowing for later resumption. If a readable stream was passed to tus-js-client, it must be closed or cancelled manually if resumption is not intended. The `shouldTerminate` argument is a boolean that determines if the upload should be terminated according to the tus termination extension. Returns a Promise resolved upon completion. ```APIDOC ## tus.Upload#abort(shouldTerminate) Abort the currently running upload request and don't continue. You can resume the upload by calling the `start` method again. Calling this method will not release the provided file because you might want to resume the upload later. If you do not want to resume and have passed a readable stream to tus-js-client, you must close/cancel the stream on your own. The `shouldTerminate` argument is a `boolean` value that determines whether or not the upload should be terminated according to the [termination extension](https://tus.io/protocols/resumable-upload.html#termination). The function returns a `Promise` object, which is resolved once the operation is complete, for example: ```js var upload = new tus.Upload(...) upload.abort(true).then(function () { // Upload has been aborted and terminated }).catch(function (err) { // An error occurred during the termination }) ``` ``` -------------------------------- ### Basic File Upload with tus-js-client Source: https://github.com/tus/tus-js-client/wiki/Blogpost-on-tus.io This snippet demonstrates how to initiate a file upload using tus-js-client when a file is selected in an input element. It configures the upload endpoint and provides a callback for successful uploads. ```javascript input.addEventListener("change", function(e) { // Get the selected file from the input element var file = e.target.files[0] // Create a new tus upload var upload = new tus.Upload(file, { endpoint: "http://localhost:1080/files/", onSuccess: function() { console.log("Download %s from %s", upload.file.name, upload.url) } }) // Start the upload upload.start() }) ``` -------------------------------- ### Run Tests in Puppeteer Source: https://github.com/tus/tus-js-client/blob/main/docs/contributing.md Run the project tests using Puppeteer, an automated browser environment. ```bash yarn run test-puppeteer ``` -------------------------------- ### uploadDataDuringCreation Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Utilizes the 'creation-with-upload' extension to transfer file content during the initial POST request. ```APIDOC ## uploadDataDuringCreation ### Description A boolean indicating whether the `creation-with-upload` extension should be used. If `true`, the file's content will already be transferred in the `POST` request when a new upload is created. This can improve upload speed as no additional `PATCH` request is needed. Please be aware that your tus server must support the [`creation-with-upload` extension](https://tus.io/protocols/resumable-upload.html#creation-with-upload) or otherwise errors will occur. ### Default value `false` ``` -------------------------------- ### Load tus-js-client with ES Modules Source: https://github.com/tus/tus-js-client/blob/main/docs/installation.md Import the tus-js-client library using ES Module syntax. This is suitable for modern bundlers. ```javascript import * as tus from 'tus-js-client' ``` -------------------------------- ### Add Metadata to New Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md The `metadata` option allows you to pass additional string key-value pairs to the server when creating a new upload. This is useful for including information like filenames or user IDs. ```javascript metadata: { filename: "my_image.png", filetype: "image/png", userId: "1234567" } ``` -------------------------------- ### uploadUrl Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md A URL which will be used to directly attempt a resume without creating an upload first. Falls back to creating a new upload if the resume attempt fails. ```APIDOC ## uploadUrl ### Description A URL which will be used to directly attempt a resume without creating an upload first. Only if the resume attempt fails it will fall back to creating a new upload using the URL specified in the `endpoint` option. Using this option may be necessary if the server is automatically creating upload resources for you, which is the case with Vimeo's API, for example. ### Default Value `null` ``` -------------------------------- ### tus.Upload.terminate(url, [options]) Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Terminates an upload based on the tus termination extension. Requires the upload URL. An optional `options` object, conforming to `tus.defaultOptions`, can be provided to specify request-related options like headers or retry delays. The function may retry the request on error, depending on the error type and `retryDelays` option. Returns a Promise resolved upon completion. ```APIDOC ## tus.Upload.terminate(url, [options]) Terminate an upload based on the [termination extension](https://tus.io/protocols/resumable-upload.html#termination). The `url` argument is the URL for the upload which you want to terminate. The `options` argument is an object with the `tus.defaultOptions` schema, which can be passed to specify certain request related options (e.g `headers`, `retryDelays`). If an error occurs during the process, the `terminate` function may retry to send the request depending on the nature of the error, and depending on whether or not the `retryDelays` options is set. The function returns a `Promise` object, which is resolved once the operation is complete, for example: ```js const url = 'https://tusd.tusdemo.net/files/my_upload_1' tus.Upload.terminate(url) .then(function () { // Upload has been terminated }) .catch(function (err) { // An error occurred during the termination }) ``` ``` -------------------------------- ### tus.defaultOptions Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An object containing the default options used when creating a new upload. This includes endpoint, fingerprinting, and various event handlers. ```APIDOC ## tus.defaultOptions ### Description An object containing the default options used when creating a new upload: #### endpoint _Default value:_ `null` The upload creation URL which will be used to create new uploads. For example: ```js endpoint: 'http://tusd.tusdemo.net/files/' ``` #### fingerprint _Default value:_ Environment-specific function A function used to generate a unique string from a corresponding file. This used to store the URL for an upload to resume. This option is only used if the `storeFingerprintForResuming` flag is set to true or when the `tus.Upload#findPreviousUploads()` method is used. To overwrite the default fingerprint method you can supply your own: ```js fingerprint: function (file, options) { const value = ... return Promise.resolve(value) } ``` #### onProgress _Default value:_ `null` An optional function that will be called each time progress information is available. The arguments will be `bytesSent` and `bytesTotal`. Please see the [FAQ](/docs/faq.md) for the difference to the `onChunkComplete` option. #### onChunkComplete _Default value:_ `null` An optional function that will be called each time a `PATCH` has been successfully completed. The arguments will be `chunkSize`, `bytesAccepted`, `bytesTotal`. Please see the [FAQ](/docs/faq.md) for the difference to the `onProgress` option. #### onSuccess _Default value:_ `null` An optional function called when the upload finished successfully. The argument will be an object with information about the completed upload. Its `lastResponse` property contains lastly received [`HttpResponse`](#httpstack), which can be used to retrieve additional data from the server. Be aware that this is usually a response to a `PATCH` request, but it might also be a response for a `POST` request (if `uploadDataDuringCreation` is enabled or an empty file is uploaded) or `HEAD` request (if an already completed upload is resumed). ```js onSuccess: function (payload) { const { lastResponse } = payload // Server can include details in the Upload-Info header, for example. console.log("Important information", lastResponse.getHeader('Upload-Info')) } ``` #### onError _Default value:_ `null` An optional function called once an error appears. The argument will be an Error instance with additional information about the involved requests. For example: ```js onError: function (err) { console.log("Error", err) console.log("Request", err.originalRequest) console.log("Response", err.originalResponse) } ``` #### onShouldRetry _Default value:_ `null` An optional function called once an error appears and before retrying. When no callback is specified, the retry behavior will be the default one: any status codes of 409, 423 or any other than 4XX will be treated as a server error and the request will be retried automatically, as long as the browser does not indicate that we are offline. When a callback is specified, its return value will influence the retry behavior: The function must return `true` if the request should be retried, `false` otherwise. The argument will be an `Error` instance with additional information about the involved requests. Please note that the callback will not be invoked when the maximum number of retry attempts was reached. ```js onShouldRetry: function (err, retryAttempt, options) { console.log("Error", err) console.log("Request", err.originalRequest) console.log("Response", err.originalResponse) var status = err.originalResponse ? err.originalResponse.getStatus() : 0 // Do not retry if the status is a 403. if (status === 403) { return false } // For any other status code, we retry. return true } ``` ``` -------------------------------- ### Handle Upload Success with onSuccess Callback Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Implement a callback function to execute upon successful upload completion. Access server response details, such as custom headers, via the `lastResponse` property. ```javascript onSuccess: function (payload) { const { lastResponse } = payload // Server can include details in the Upload-Info header, for example. console.log("Important information", lastResponse.getHeader('Upload-Info')) } ``` -------------------------------- ### parallelUploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Configures the number of parts to upload in parallel, utilizing the concatenation extension. ```APIDOC ## parallelUploads ### Description A number indicating how many parts should be uploaded in parallel. If this number is not `1`, the input file will be split into multiple parts, where each part is uploaded individually in parallel. The value of `parallelUploads` determines the number of parts. Using `parallelUploadBoundaries` the size of each part can be changed. After all parts have been uploaded, the [`concatenation` extension](https://tus.io/protocols/resumable-upload.html#concatenation) will be used to concatenate all the parts together on the server-side, so the tus server must support this extension. This option should not be used if the input file is a streaming resource. ### Default value `1` ``` -------------------------------- ### Upload to Vimeo Using uploadUrl Source: https://github.com/tus/tus-js-client/blob/main/docs/usage.md Upload a file to Vimeo by providing the pre-generated upload URL from the Vimeo API. This bypasses the need for the `endpoint` option. ```javascript // Obtain video to upload from user input or similar var file = ... // The upload URL you get from the Vimeo API for uploading var uploadUrl = ... // Create the tus upload similar to the example from above var upload = new tus.Upload(file, { uploadUrl: uploadUrl, onError: function(error) { console.log("Failed because: " + error) }, onSuccess: function() { console.log("Download %s from %s", upload.file.name, upload.url) } }) // Start the upload upload.start() ``` -------------------------------- ### Include tus-js-client via Script Tag Source: https://github.com/tus/tus-js-client/wiki/Blogpost-on-tus.io This shows how to include the tus-js-client library in an HTML document using a script tag, making it available for use in your web application. ```html ``` -------------------------------- ### Set Custom Headers for Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Use the `headers` option to include custom HTTP headers in all requests made by the client. This is commonly used for authentication tokens. ```javascript headers: { "Authorization": "Bearer ..." } ``` -------------------------------- ### Check Browser Support with tus.isSupported Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Use this boolean to test if the current browser environment supports tus-js-client features. It helps in providing user feedback or implementing fallback mechanisms. ```javascript if (!tus.isSupported) { alert('This browser does not support uploads. Please use a modern browser instead.') } ``` -------------------------------- ### Abort Upload and Terminate Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Use this to abort an ongoing upload and terminate it according to the tus termination extension. The promise resolves when the operation is complete. Ensure to handle potential errors during termination. ```javascript var upload = new tus.Upload(...) upload.abort(true).then(function () { // Upload has been aborted and terminated }).catch(function (err) { // An error occurred during the termination }) ``` -------------------------------- ### Override PATCH Method with POST Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Set `overridePatchMethod` to `true` to use `POST` requests with an `X-HTTP-Method-Override: PATCH` header instead of `PATCH` requests. This is a fallback for environments that do not support `PATCH`. ```javascript overridePatchMethod: false ``` -------------------------------- ### Process Response After Receiving (onAfterResponse) Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Use this callback to process HTTP responses. It receives HttpRequest and HttpResponse instances. Useful for retrieving custom headers or performing actions based on the response. ```javascript onAfterResponse: function (req, res) { var url = req.getURL() var value = res.getHeader("X-My-Header") console.log(`Request for ${url} responded with ${value}`) } ``` ```javascript onAfterResponse: function (req, res) { return new Promise(resolve => { var url = req.getURL() var value = res.getHeader("X-My-Header") console.log(`Request for ${url} responded with ${value}`) resolve() }) } ``` -------------------------------- ### uploadSize Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An optional integer representing the size of the file in bytes. This will only be used if the size cannot be automatically calculated. ```APIDOC ## uploadSize ### Description An optional integer representing the size of the file in bytes. This will only be used if the size cannot be automatically calculated which only happens if you supply a `Readable` stream as the file to upload. ### Default Value `null` ``` -------------------------------- ### Control Retries with onShouldRetry Callback Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Implement a callback to determine whether an upload should be retried after an error. Return `true` to retry, `false` to abort. This allows custom retry logic based on error details like status codes. ```javascript onShouldRetry: function (err, retryAttempt, options) { console.log("Error", err) console.log("Request", err.originalRequest) console.log("Response", err.originalResponse) var status = err.originalResponse ? err.originalResponse.getStatus() : 0 // Do not retry if the status is a 403. if (status === 403) { return false } // For any other status code, we retry. return true } ``` -------------------------------- ### UrlStorage Interface Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Defines the interface for custom URL storage implementations. This allows for persistent storage of upload URLs across sessions. ```APIDOC interface UrlStorage { findAllUploads(): Promise> findUploadsByFingerprint(fingerprint: string): Promise> removeUpload(urlStorageKey: string): Promise // Returns the URL storage key, which can be used for removing the upload. addUpload(fingerprint: string, upload: ListEntry): Promise } interface ListEntry { size: number | null metadata: object creationTime: string urlStorageKey: string uploadUrl: string | null parallelUploadUrls: string[] | null } ``` -------------------------------- ### Specify Upload URL for Resuming Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md The `uploadUrl` option provides a direct URL to attempt resuming an upload without initiating a new one. This is useful when the server pre-creates upload resources. ```javascript uploadUrl: null ``` -------------------------------- ### tus.Upload#url Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md The URL used to upload the file. This property is set once an upload has been created, typically when the onSuccess callback is invoked. To resume an upload from a specific URL, use the `uploadUrl` option instead. ```APIDOC ## tus.Upload#url The URL used to upload the file. This property will be set once an upload has been created, which happens at last when the `onSuccess` callback is invoked. To resume an upload from a specific URL use the `uploadUrl` option instead. ``` -------------------------------- ### metadata Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An object with string values used as additional meta data which will be passed along to the server when creating a new upload. ```APIDOC ## metadata ### Description An object with string values used as additional meta data which will be passed along to the server when (and only when) creating a new upload. Can be used for filenames, file types etc, for example: ```js metadata: { filename: "my_image.png", filetype: "image/png", userId: "1234567" } ``` ### Default Value `{}` ``` -------------------------------- ### onBeforeRequest Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An optional function that will be called before a HTTP request is sent out. It receives an instance of the `HttpRequest` interface and can be used to modify the outgoing request. It can also return a Promise for asynchronous operations. ```APIDOC ## onBeforeRequest ### Description An optional function that will be called before a HTTP request is sent out. The argument will be an instance of the `HttpRequest` interface as defined for the `httpStack` option. This can be used to modify the outgoing request. For example, you can enable the `withCredentials` setting for XMLHttpRequests in browsers. ### Example (Synchronous) ```javascript onBeforeRequest: function (req) { var xhr = req.getUnderlyingObject() xhr.withCredentials = true } ``` ### Example (Asynchronous with Promise) ```javascript onBeforeRequest: function (req) { return new Promise(resolve => { var xhr = req.getUnderlyingObect() xhr.withCredentials = true resolve() }) } ``` ``` -------------------------------- ### metadataForPartialUploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An object with string values used as additional meta data for partial uploads. This option has no effect if parallel uploads are not enabled. ```APIDOC ## metadataForPartialUploads ### Description An object with string values used as additional meta data for partial uploads. When parallel uploads are enabled via `parallelUploads`, tus-js-client creates multiple partial uploads. The values from `metadata` are not passed to these partial uploads but only passed to the final upload, which is the concatentation of the partial uploads. In contrast, the values from `metadataForPartialUploads` are only passed to the partial uploads and not the final upload. This option has no effect if parallel uploads are not enabled. Can be used to associate partial uploads to a user, for example: ```js metadataForPartialUploads: { userId: "1234567" } ``` ### Default Value `{}` ``` -------------------------------- ### headers Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An object with custom header values used in all requests. Useful for adding authentication details. ```APIDOC ## headers ### Description An object with custom header values used in all requests. Useful for adding authentication details, for example: ```js headers: { "Authorization": "Bearer ..." } ``` ### Default Value `{}` ``` -------------------------------- ### httpStack Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An object used as the HTTP stack for making network requests. It provides an abstraction layer over different network APIs. You can implement your own HTTP stack by providing an object conforming to the `HttpStack` interface. ```APIDOC ## httpStack ### Description An object used as the HTTP stack for making network requests. This is an abstraction layer above the different network APIs on the various platforms. If you want to implement your own HTTP stack, pass an object to the `httpStack` option which conforms to the following `HttpStack` interface. ### Interface Definition ```typescript interface HttpStack { createRequest(method: string, url: string): HttpRequest; getName(): string; } interface HttpRequest { constructor(method: string, url: string); getMethod(): string; getURL(): string; // Set a header from this request. setHeader(header: string, value: string); // Retrieve a header value from this request. // Note: In browser environments this method can only return headers explicitly set by // tus-js-client or users through the above `setHeader` method. It cannot return headers that are // implicitly added by the browser (e.g. Content-Length) due to a security related API limitation. getHeader(header: string): string | undefined; setProgressHandler((bytesSent: number): void): void; // Send the HTTP request with the provided request body. The value of the request body depends // on the platform and what `fileReader` implementation is used. With the default `fileReader`, // `body` can be // - in browsers: a TypedArray, a DataView a Blob, or null. // - in Node.js: a Buffer, a ReadableStream, or null. send(body: any): Promise; // Aborts the request if it's currently in progress. If so, `send` should reject // with an error of type DOMException, with name AbortError. abort(): Promise; // Return an environment specific object, e.g. the XMLHttpRequest object in browsers. getUnderlyingObject(): any; } interface HttpResponse { getStatus(): number; getHeader(header: string): string | undefined; getBody(): string; // Return an environment specific object, e.g. the XMLHttpRequest object in browsers. getUnderlyingObject(): any; } ``` ``` -------------------------------- ### Set Upload Size for Streams Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md The `uploadSize` option is an integer representing the file size in bytes. It is primarily used when uploading a `Readable` stream where the size cannot be automatically determined. ```javascript uploadSize: null ``` -------------------------------- ### Add Metadata for Partial Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Use `metadataForPartialUploads` to provide metadata specifically for partial uploads when `parallelUploads` is enabled. These values are not sent with the final concatenated upload. ```javascript metadataForPartialUploads: { userId: "1234567" } ``` -------------------------------- ### Configure Chunk Size for PATCH Requests Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md The `chunkSize` option limits the size of `PATCH` request bodies in bytes. It is required when uploading streams and should generally be left at its default (`Infinity`) for optimal performance unless server limitations or specific stream handling necessitate its use. ```javascript chunkSize: Infinity ``` -------------------------------- ### onAfterResponse Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md An optional function that will be called after a HTTP response has been received. It receives `HttpRequest` and `HttpResponse` instances and can be used to retrieve additional data from the server. It can also return a Promise for asynchronous operations. ```APIDOC ## onAfterResponse ### Description An optional function that will be called after a HTTP response has been received. The arguments will be an instance of the `HttpRequest` and `HttpResponse` interface as defined for the `httpStack` option. This can be used to retrieve additional data from the server, for example. ### Example (Synchronous) ```javascript onAfterResponse: function (req, res) { var url = req.getURL() var value = res.getHeader("X-My-Header") console.log(`Request for ${url} responded with ${value}`) } ``` ### Example (Asynchronous with Promise) ```javascript onAfterResponse: function (req, res) { return new Promise(resolve => { var url = req.getURL() var value = res.getHeader("X-My-Header") console.log(`Request for ${url} responded with ${value}`) resolve() }) } ``` ``` -------------------------------- ### overridePatchMethod Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md A boolean indicating whether the POST method should be used instead of PATCH for transferring the chunks. This may be necessary if a browser or the server does not support the latter. ```APIDOC ## overridePatchMethod ### Description A boolean indicating whether the `POST` method should be used instead of `PATCH` for transferring the chunks. This may be necessary if a browser or the server does not support latter one. In this case, a `POST` request will be made with the `X-HTTP-Method-Override: PATCH` header. The server must be able to detect it, and then handle the request as if `PATCH` would have been the method. ### Default Value `false` ``` -------------------------------- ### UrlStorage Interface Definition Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Defines the interface for custom URL storage implementations. Use this to manage upload URLs across sessions. ```typescript interface UrlStorage { findAllUploads(): Promise> findUploadsByFingerprint(fingerprint: string): Promise> removeUpload(urlStorageKey: string): Promise // Returns the URL storage key, which can be used for removing the upload. addUpload(fingerprint: string, upload: ListEntry): Promise } ``` ```typescript interface ListEntry { size: number | null metadata: object creationTime: string urlStorageKey: string uploadUrl: string | null parallelUploadUrls: string[] | null } ``` -------------------------------- ### Custom HTTP Stack Interface Definition Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Defines the interface for a custom HTTP stack, including methods for creating requests and retrieving the stack name. This allows for custom network request implementations. ```typescript interface HttpStack { createRequest(method: string, url: string): HttpRequest; getName(): string; } interface HttpRequest { constructor(method: string, url: string); getMethod(): string; getURL(): string; // Set a header from this request. setHeader(header: string, value: string); // Retrieve a header value from this request. // Note: In browser environments this method can only return headers explicitly set by // tus-js-client or users through the above `setHeader` method. It cannot return headers that are // implicitly added by the browser (e.g. Content-Length) due to a security related API limitation. getHeader(header: string): string | undefined; setProgressHandler((bytesSent: number): void): void; // Send the HTTP request with the provided request body. The value of the request body depends // on the platform and what `fileReader` implementation is used. With the default `fileReader`, // `body` can be // - in browsers: a TypedArray, a DataView a Blob, or null. // - in Node.js: a Buffer, a ReadableStream, or null. send(body: any): Promise; // Aborts the request if it's currently in progress. If so, `send` should reject // with an error of type DOMException, with name AbortError. abort(): Promise; // Return an environment specific object, e.g. the XMLHttpRequest object in browsers. getUnderlyingObject(): any; } interface HttpResponse { getStatus(): number; getHeader(header: string): string | undefined; getBody(): string; // Return an environment specific object, e.g. the XMLHttpRequest object in browsers. getUnderlyingObject(): any; } ``` -------------------------------- ### Customize Fingerprint for Resumable Uploads Source: https://github.com/tus/tus-js-client/blob/main/docs/api.md Provide a custom function to generate a unique identifier for a file, used for resuming uploads. This is crucial when `storeFingerprintForResuming` is true or when using `findPreviousUploads`. ```javascript fingerprint: function (file, options) { const value = ... return Promise.resolve(value) } ```