"use client"; import { useState, useRef } from "react"; import * as tus from "tus-js-client"; const UploadDemo: React.FC = () => { const [upload, setUpload] = useState(null); const [uploadIsRunning, setUploadIsRunning] = useState(false); const [uploadProgress, setUploadProgress] = useState(0); const fileInputRef = useRef(null); const endpointInputRef = useRef(null); const chunkSizeInputRef = useRef(null); const parallelUploadsInputRef = useRef(null); const startUpload = () => { if (fileInputRef.current && fileInputRef.current.files) { const file = fileInputRef.current.files[0]; if (!file) return; const endpoint = endpointInputRef.current?.value || ""; const chunkSize = parseInt(chunkSizeInputRef.current?.value || "", 10) || Infinity; const parallelUploads = parseInt(parallelUploadsInputRef.current?.value || "", 10) || 1; var mediaId = ""; const options: tus.UploadOptions = { endpoint: "http://localhost:3000/api/cloudflare", // chunkSize: 50 * 1024 * 1024, retryDelays: [0, 1000, 3000, 5000], // parallelUploads: parallelUploads, metadata: { expiry: "2024-03-27T04:45:19.634Z", filename: file.name, filetype: file.type, }, onError: (error) => { console.log( "This is the famous error", JSON.stringify(error.message) ); alert(`Failed because: ${error}`); reset(); }, onProgress: (bytesUploaded, bytesTotal) => { const percentage = (bytesUploaded / bytesTotal) * 100; setUploadProgress(percentage); }, // onBeforeRequest: function (req) { // const xhr = req.getUnderlyingObject(); // xhr.withCredentials = true; // }, onSuccess: () => { console.log("Upload finished:", newUpload.url); alert(newUpload.url); // var index = newUpload.url!.lastIndexOf("/") + 1; // var mediaId = newUpload.url!.substr(index); // console.log("Media id:", mediaId); reset(); }, onAfterResponse: function (req, res) { return new Promise((resolve) => { var mediaIdHeader = res.getHeader("stream-media-id"); if (mediaIdHeader) { mediaId = mediaIdHeader; } console.log(mediaId); resolve(); }); }, }; const newUpload = new tus.Upload(file, options); newUpload.start(); setUpload(newUpload); setUploadIsRunning(true); } }; const toggleUpload = () => { if (upload) { if (uploadIsRunning) { upload.abort(); setUploadIsRunning(false); } else { upload.start(); setUploadIsRunning(true); } } else { startUpload(); } }; const reset = () => { if (fileInputRef.current) fileInputRef.current.value = ""; setUpload(null); setUploadIsRunning(false); setUploadProgress(0); }; return (

tus-js-client demo - File Upload

This demo shows the basic functionality of the tus protocol. You can select a file using the controls below and start/pause the upload as you wish.

For a prettier demo please go to the{" "} tus.io {" "} website. This demo is just here to aid developers.

{/*

Warning!

Your browser may not support all features necessary to run tus-js-client. Some functionalities might fail silently.

*/}

Uploads

Successful uploads will be listed here. Try one!

); }; export default UploadDemo;