A file upload web component
npm install @chunkify/uploader

Chunkify Uploader is a fully customizable web component that makes it easy to upload a video file to Chunkify.
It allows you to easily integrate a video upload UI in your application.
Chunkify Uploader supports:
- File selection
- Drag and drop for files
- Full UI Customization
> ⚠️ Important: A React component is also available. Check the full documentation to see how to use it.
``bash`
npm install @chunkify/uploader@latest
`html`
The CSS styling by default is very minimal so you will have to provide your own styling to make it looks good.
Here is a simple implementation with some simple CSS styling with a drop zone available, a file select button, a progress bar and text, an error and finally a success message.
`html HTML
`
Chunkify Uploader allows you to use upload URLs provided by Chunkify Upload API via the endpoint property / attribute.
This means that you'll need to provide a new upload URL whenever a user will be uploading a new video file in your application.
`html `
The endpoint indicates the direct upload URL that will receive the selected file.
You can generate a presigned upload URL using the Chunkify Upload API
In a successful API response, you will get a unique presigned upload URL that you can use to upload the file and set as an endpoint of the Chunkify Uploader.
Depending on your workflow, at the time you render the Chunkify Uploader, you might not have the upload URL yet. You might want to fetch it asynchronously after the user selected a file.
To this effect you can use the endpoint property and set it to a custom function that will return the upload URL.
Note: The file upload is done using the PUT method, so you will need to use thePUT method to upload the file to this URL.
`html HTML
`
#### Server-side endpoint example
Since upload URLs are temporary and should be generated per upload, you'll need a server endpoint that creates them on-demand. Here's a complete Express.js and Next.js example:
What this endpoint does:
- Receives requests from your frontend when users want to upload
- Creates a new upload entry via Chunkify API
- Returns the temporary upload URL to your Chunkify Uploader component
`javascript Express.js
import { RequestHandler } from 'express';
import { Chunkify } from '@chunkify/chunkify';
import express from 'express';
import cors from 'cors';
const app = express();
// CORS configuration
app.use(cors({
origin: ['http://your.frontend.url:port'],
methods: ['POST'],
allowedHeaders: ['Content-Type'],
}));
const PORT = 8787;
// Middleware
app.use(express.json());
app.use(express.static('public'));
const uploadHandler: RequestHandler = async (req, res) => {
try{
const client = new Chunkify({
projectAccessToken:'your_project_token',
});
// Create the upload entry
const upload = await client.uploads.create({})
// Return the upload URL
res.send(upload.upload_url);
} catch (error) {
// Handle errors if any
if (error instanceof Chunkify.APIError) {
res.status(error.status || 500).json({ error: error.message });
} else {
res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
}
}
};
// Set the route
app.post('/api/upload', uploadHandler);
// Start the server
app.listen(PORT, () => {
console.log(Server running at http://localhost:${PORT});
});
`
#### Enable drag and drop
You can enable drag and drop uploads using the attribute / property drop. The drop zone will be the entire component.
`html HTML`
#### File size limit
You can configure the following attribute / property : max-file-size / maxFileSize to set the maximum size in MB accepted by the uploader. Any larger file will trigger an error.
`html HTML`
The uploader emits events throughout the upload lifecycle, allowing you to listen and respond with custom logic.
Chunkify Uploader has a dynamic UI that changes based on the current upload state.
Here is a list of the states and their respective description:
| State | Attribute | Description |
| --------- | ----------- | ---------------------------------------- |
| Initial | (none) | Initial status before a file is selected |
| Uploading | uploading | Upload in progress |success
| Completed | | File successfully uploaded |error
| Error | | Error during the upload process |
#### Traditional Event Listeners
For example, you can listen to the upload-progress event to receive details about the progress of the upload.
`typescript Javascript
const chunkifyUploader = document.querySelector('chunkify-uploader');
chunkifyUploader.addEventListener('upload-progress', (event) => {
console.log('Upload progress is ' + event.detail.progress + '%');
});
`
#### Function Property Shortcuts
You can also use function properties provided to simplify the process if you so desire.
`typescript
const chunkifyUploader = document.querySelector('chunkify-uploader');
chunkifyUploader.onUploadProgress = (event) => {
console.log('Upload progress is ' + event.detail.progress + '%');
};
`
Here are all the events, when they will fire, and what they hold:
| Event name | Function Property | Trigger | Event detail |
| ----------------- | ----------------- | --------------------------------- | ----------------------------------- |
| upload-progress | onUploadProgress | When upload status updates | { progress: number } |upload-error
| | onUploadError | When upload fails | { error: string, status: number } |upload-success
| | onUploadSuccess | When upload complete successfully | { file: File } |file-selected
| | onFileSelected | When a file is selected | { file: File } |
#### Example
Here we display in the console the uploaded file name when the upload is complete or the error message and its status code when an error occurs.
`html HTML
...
`
Using the chunkify-uploader-error sub component is the way to display errors to the user.
`html HTML`
The message "Error: Upload Failed" will be displayed when an error occurs during the upload process. If you want to customize it depending on the error you can use the upload-error event discussed above.max-file-size
File processing errors such as exceeded, API and network errors will be handled by the uploader.
Note: Only two types of errors are not customizable: first if the user chose a file that exceeds the max-file-size and second if an endpoint has not been set.
The error message will be displayed in both cases where the component has been used.
Chunkify Uploader web component is built to be fully customizable to match you project design. It comes with sub components that you will need to use to and style.
You can and must override all components CSS except the progress bar where you must use the CSS variables provided to customize it.
Note: By default the main component
| Name | Description | CSS Override | Displayed When |
| ----------------------------------- | ------------------------------ | ----------------- | -------------- |
| | Main component | Yes | Always |
| | File selector button | Yes | Initial |
| | Heading / Title | Yes | Initial |
| | Progress Percent | Yes | Uploading |
| | Progress Bar | Use CSS variables | Uploading |
| | Error message | Yes | Upload Error |
| | Reset to initital state button | Yes | Upload Error |
| | Success message | Yes | Upload Success |
Here is a very basic uploader component example with just a button to upload a file.
`html HTML
`
The progress bar has a default appareance and color but some CSS variables are available to customize the component. This allows you to tweak the progress bar appearance:
| Name | CSS Property | Description |
| ----------------------- | ------------------ | ------------------------------------ |
| --progress-fill-color | background-color | Color of the progress bar |--progress-background
| | background-color | Background color of the progress bar |--progress-height
| | height | Height of the progress bar |--progress-width
| | width | Width of the progress bar |--progress-radius
| | border-radius | Radius of the progress bar |--progress-border
| | border | Border of the progress bar |
You can use them like this:
`html HTML
`
Include Tailwind CSS and you can start sytling with it with the classattribute.
`html HTML
class="
h-1/2
bg-white
[&[dragover]]:bg-blue-100
[&[uploading]]:bg-orange-100
[--progress-fill-color:green]
"
>
...
`
If you enable drag and drop uploads using the attribute / property drop, the drag and drop zone will be the entire component.
You can use the attribute dragoverto style your component appropriately.
In React you can use CSS-in-JS, for example, using CSS modules.
Here is a full example with drag and drop enabled.
`HTML HTML
...
`
Chukify Uploader uses properties and attributes to manage different states changes during the upload process.
| State | Attribute | Description |
| --------- | ----------- | ---------------------------------------- |
| Initial | (none) | Initial status before a file is selected |
| Uploading | uploading | Upload in progress |success
| Completed | | File successfully uploaded |error
| Error | | Error during the upload process |
This allows to use attribute selectors for state-driven styling via CSS.
In React you can use CSS-in-JS, for example, using CSS modules.
Here is a basic example where we change the background color of the uploader when the upload is completed or in error:
`HTML HTML
`
You can further customize UI by using events. For example, you can write a custom common error message that will display when an upload error occurs but you can fine tune it depending on the detail of the event.
Here a basic example of how to do that :
`javascript HTML
`
In the example above the error message will be "Error during the upload" except if the status code is 404 in which case it will display "Upload URL not found".
#### Display file information
When your user select a file or when the upload completes successfully, you have access to the File object through the event.
Here is an example on how you can display these infos during the upload and on upload success, we added a ".my-file-info" div to display the info about the file that is display: noneby default and that we set on display: block when the upload is in progress.
Note: You will need to to use the uploading attribute to display the info only
during the upload process.
`javascript
`
Chunkify Uploader is built to work with Chunkify Uploads API and its workflow. You will need to use webhooks to receive notifications about the upload process.
To learn more about webhooks, please see the complete Chunkify documentation.
Uploading a video file takes time and can vary depending on the size of the file and the network conditions.
Chunkify uses webhooks to notify you of your uploads statuses.
The workflow goes generally like this:
#### 1. Setup webhooks and API endpoint
- Set up a public webhook endpoint in your application to receive events from Chunkify
- Configure the webhook in your Chunkify dashboard to send events to this endpoint
#### 2. Upload the video
- Create an upload URL using Chunkify API.
- Save relevant information in your database, the upload ID for example.
- Pass the URL to the endpoint attribute of the Chunkify Uploader (see Setup section)
#### 3. Handle webhooks events
Listen for specific events:
- upload.completed: The upload is completed and the source is created you can start a transcoding job using the source_id contained in the payload.upload.failed
- : The upload failed, you can retry the upload or delete the upload.upload.expired
- : The upload expired, upload entry was created but no file was sent to the URL during its lifetime.
#### 4. Store information about the upload
Once the upload is completed and you receive the event, you can save the source_id found in the upload.completed event payload associating it with a relevant entity in your application.
> 💡 Tip: You can pass metadata during upload creation to help with your workflow. Any metadata you include in the upload will be automatically copied to the source metadata. For example, If you want to link a source to a specific user, include the user_id in the upload metadata. This user_id` will then be available in the source metadata, making it easy to track which user uploaded which content.