tus.mdx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. ---
  2. sidebar_position: 2
  3. slug: /tus
  4. ---
  5. import Tabs from '@theme/Tabs';
  6. import TabItem from '@theme/TabItem';
  7. import UppyCdnExample from '/src/components/UppyCdnExample';
  8. # Tus
  9. The `@uppy/tus` plugin brings resumable file uploading with [Tus](http://tus.io)
  10. to Uppy by wrapping the [`tus-js-client`][].
  11. ## When should I use it?
  12. :::tip
  13. Not sure which uploader is best for you? Read
  14. “[Choosing the uploader you need](/docs/guides/choosing-uploader)”.
  15. :::
  16. [Tus][tus] is an open protocol for resumable uploads built on HTTP. This means
  17. accidentally closing your tab or losing connection let’s you continue, for
  18. instance, your 10GB upload instead of starting all over.
  19. Tus supports any language, any platform, and any network. It requires a client
  20. and server integration to work. You can checkout the client and server
  21. [implementations][] to find the server in your preferred language. You can store
  22. files on the Tus server itself, but you can also use service integrations (such
  23. as S3) to store files externally. If you don’t want to host your own server, see
  24. “[Are there hosted Tus servers?](#are-there-hosted-tus-servers)”.
  25. If you want reliable, resumable uploads: use `@uppy/tus` to connect to your Tus
  26. server in a few lines of code.
  27. ## Install
  28. <Tabs>
  29. <TabItem value="npm" label="NPM" default>
  30. ```shell
  31. npm install @uppy/tus
  32. ```
  33. </TabItem>
  34. <TabItem value="yarn" label="Yarn">
  35. ```shell
  36. yarn add @uppy/tus
  37. ```
  38. </TabItem>
  39. <TabItem value="cdn" label="CDN">
  40. <UppyCdnExample>
  41. {`
  42. import { Uppy, Tus } from "{{UPPY_JS_URL}}"
  43. new Uppy().use(Tus, { endpoint: 'https://tusd.tusdemo.net/files' })
  44. `}
  45. </UppyCdnExample>
  46. </TabItem>
  47. </Tabs>
  48. ## Use
  49. A quick overview of the complete API.
  50. ```js {10} showLineNumbers
  51. import Uppy from '@uppy/core';
  52. import Dashboard from '@uppy/dashboard';
  53. import Tus from '@uppy/tus';
  54. import '@uppy/core/dist/style.min.css';
  55. import '@uppy/dashboard/dist/style.min.css';
  56. new Uppy()
  57. .use(Dashboard, { inline: true, target: 'body' })
  58. .use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/' });
  59. ```
  60. ## API
  61. ### Options
  62. :::info
  63. All options are passed to `tus-js-client` and we document the ones here that are
  64. required, added, or changed. This means you can also pass functions like
  65. [`onAfterResponse`](https://github.com/tus/tus-js-client/blob/master/docs/api.md#onafterresponse).
  66. We recommended taking a look at the
  67. [API reference](https://github.com/tus/tus-js-client/blob/master/docs/api.md)
  68. from `tus-js-client` to know what is supported.
  69. :::
  70. #### `id`
  71. A unique identifier for this plugin (`string`, default: `'Tus'`).
  72. #### `endpoint`
  73. URL of the tus server (`string`, default: `null`).
  74. #### `headers`
  75. An object or function returning an object with HTTP headers to send along
  76. requests (`object | function`, default: `null`).
  77. Keys are header names, values are header values.
  78. ```js
  79. const headers = {
  80. authorization: `Bearer ${window.getCurrentUserToken()}`,
  81. };
  82. ```
  83. Header values can also be derived from file data by providing a function. The
  84. function receives an [Uppy file][] and must return an object where the keys are header
  85. names, and values are header values.
  86. ```js
  87. const headers = (file) => {
  88. return {
  89. authorization: `Bearer ${window.getCurrentUserToken()}`,
  90. expires: file.meta.expires,
  91. };
  92. };
  93. ```
  94. #### `chunkSize`
  95. A number indicating the maximum size of a `PATCH` request body in bytes
  96. (`number`, default: `Infinity`). Note that this option only affects local
  97. browser uploads. If you need a max chunk size for remote (Companion) uploads,
  98. you must set the `chunkSize` Companion option as well.
  99. :::caution
  100. Do not set this value unless you are forced to. The two valid reasons are
  101. described in the
  102. [`tus-js-client` docs](https://github.com/tus/tus-js-client/blob/master/docs/api.md#chunksize).
  103. :::
  104. #### `withCredentials`
  105. Configure the requests to send Cookies using the
  106. [`xhr.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials)
  107. property (`boolean`, default: `false`).
  108. The remote server must accept CORS and credentials.
  109. #### `retryDelays`
  110. When uploading a chunk fails, automatically try again after the defined
  111. millisecond intervals (`Array<number>`, default: `[0, 1000, 3000, 5000]`).
  112. By default, we first retry instantly; if that fails, we retry after 1 second; if
  113. that fails, we retry after 3 seconds, etc.
  114. Set to `null` to disable automatic retries, and fail instantly if any chunk
  115. fails to upload.
  116. #### `onBeforeRequest(req, file)`
  117. Behaves like the
  118. [`onBeforeRequest`](https://github.com/tus/tus-js-client/blob/master/docs/api.md#onbeforerequest)
  119. function from `tus-js-client` but with the added `file` argument.
  120. #### `onShouldRetry: (err, retryAttempt, options, next)`
  121. When an upload fails `onShouldRetry` is called with the error and the default
  122. retry logic as the last argument (`function`).
  123. The default retry logic is an
  124. [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff)
  125. algorithm triggered on HTTP 429 (Too Many Requests) errors. Meaning if your
  126. server (or proxy) returns HTTP 429 because it’s being overloaded, @uppy/tus will
  127. find the ideal sweet spot to keep uploading without overloading.
  128. If you want to extend this functionality, for instance to retry on unauthorized
  129. requests (to retrieve a new authentication token):
  130. ```js
  131. import Uppy from '@uppy/core';
  132. import Tus from '@uppy/tus';
  133. new Uppy().use(Tus, {
  134. endpoint: '',
  135. async onBeforeRequest(req) {
  136. const token = await getAuthToken();
  137. req.setHeader('Authorization', `Bearer ${token}`);
  138. },
  139. onShouldRetry(err, retryAttempt, options, next) {
  140. if (err?.originalResponse?.getStatus() === 401) {
  141. return true;
  142. }
  143. return next(err);
  144. },
  145. async onAfterResponse(req, res) {
  146. if (res.getStatus() === 401) {
  147. await refreshAuthToken();
  148. }
  149. },
  150. });
  151. ```
  152. #### `allowedMetaFields`
  153. Pass an array of field names to limit the metadata fields that will be added to
  154. uploads as
  155. [Tus Metadata](https://tus.io/protocols/resumable-upload.html#upload-metadata)
  156. (`Array`, default: `null`).
  157. - Set it to `false` to not send any fields (or an empty array).
  158. - Set it to `['name']` to only send the `name` field.
  159. - Set it to `true` (the default) to send _all_ metadata fields.
  160. #### `limit`
  161. Limit the amount of uploads going on at the same time (`number`, default: `20`).
  162. Setting this to `0` means no limit on concurrent uploads (not recommended).
  163. ## Frequently Asked Questions
  164. :::info
  165. The Tus website has extensive [FAQ section](https://tus.io/faq.html), we
  166. recommend taking a look there as well if something is unclear.
  167. :::
  168. ### How is file meta data stored?
  169. Tus uses unique identifiers for the file names to prevent naming collisions. To
  170. still keep the meta data in place, Tus also uploads an extra `.info` file with
  171. the original file name and other meta data:
  172. ```json
  173. {
  174. "ID": "00007a99d16d4eeb5a3e3c080b6f69da+JHZavdqPSK4VMtarg2yYcNiP8t_kDjN51lBYMJdEyr_wqEotVl8ZBRBSTnWKWenZBwHvbLNz5tQXYp2N7Vdol.04ysQAuw__suTJ4IsCljj0rjyWA6LvV4IwF5P2oom2",
  175. "Size": 1679852,
  176. "SizeIsDeferred": false,
  177. "Offset": 0,
  178. "MetaData": {
  179. "filename": "cat.jpg",
  180. "filetype": "image/jpeg"
  181. },
  182. "IsPartial": false,
  183. "IsFinal": false,
  184. "PartialUploads": null,
  185. "Storage": {
  186. "Bucket": "your-bucket",
  187. "Key": "some-key",
  188. "Type": "s3store"
  189. }
  190. }
  191. ```
  192. ### How do I change files before sending them?
  193. If you want to change the file names, you want to do that in
  194. [`onBeforeFileAdded`](/docs/uppy#onbeforefileaddedfile-files).
  195. If you want to send extra headers with the request, use [`headers`](#headers) or
  196. [`onBeforeRequest`](#onbeforerequestreq-file).
  197. ### How do I change (or move) files after sending them?
  198. If you want to preserve files names, extract meta data, or move files to a
  199. different place you generally can with hooks or events. It depends on the Tus
  200. server you use how it’s done exactly. [`tusd`][], for instance, exposes
  201. [hooks](https://github.com/tus/tusd/blob/master/docs/hooks.md) and
  202. [`tus-node-server`](https://github.com/tus/tus-node-server) has
  203. [events](https://github.com/tus/tus-node-server#events).
  204. ### Which server do you recommend?
  205. [Transloadit](https://transloadit.com) runs [`tusd`][] in production, where it
  206. serves millions of requests globally. So we recommend `tusd` as battle-tested
  207. from our side, but other companies have had success with other
  208. [implementations][] so it depends on your needs.
  209. ### Are there hosted Tus servers?
  210. All [Transloadit plans](https://transloadit.com/pricing) come with a hosted
  211. [`tusd`][] server. You don’t have to do anything to leverage it, using
  212. [`@uppy/transloadit`](/docs/transloadit) automatically uses Tus under the hood.
  213. ### Why Tus instead of directly uploading to AWS S3?
  214. First: reliable, resumable uploads. This means accidentally closing your tab or
  215. losing connection let’s you continue, for instance, your 10GB upload instead of
  216. starting all over.
  217. Tus is also efficient with lots of files (such as 8K) and large files. Uploading
  218. to AWS S3 directly from the client also introduces quite a bit of overhead, as
  219. more requests are needed for the flow to work.
  220. [`tus-js-client`]: https://github.com/tus/tus-js-client
  221. [uppy file]: /docs/uppy#working-with-uppy-files
  222. [tus]: https://tus.io/
  223. [`tusd`]: https://github.com/tus/tusd
  224. [implementations]: https://tus.io/implementations.html