Upload videos directly
FastPix Direct Uploads provide a streamlined solution for uploading media (video and audio) directly to your platform from client applications. This guide will simplify the process and highlight how users can effectively utilize authenticated upload URLs for seamless content delivery.
Key benefits of FastPix direct uploads
- Authenticated access: Grant authenticated access for direct uploads from mobile and web applications, ensuring secure and controlled content management.
- Flexible upload options: Upload media directly from your server or use command-line tools, providing ultimate flexibility in how you manage your media.
- Storage efficiency: Eliminate the need to store original files on your local system, reducing storage costs and simplifying file management.
- Better user experience: Deliver exceptional experiences to your audience with efficient content delivery, reducing loading times and improving accessibility.
Use case scenarios
FastPix Direct Uploads can be utilized in multiple scenarios:
- Mobile app uploads: Users can upload videos directly from their mobile devices, enhancing user-generated content (UGC) capabilities.
- Web app uploads: Web applications can facilitate direct uploads, allowing users to share content easily.
- Server-side content uploads: Large platforms can upload media files in batches from their servers, streamlining content management.
- Command-line tool uploads: Developers can leverage command-line tools for quick and efficient uploads, perfect for automated workflows.
Uploading media to FastPix in 3 steps
Step 1: Generate a unique upload URL
- Generate an access token: Create a new Access Token in FastPix dashboard. This token consists of a Token ID (username) and Token Secret (password) pair, which are necessary for authenticating with the FastPix Video API.
- Make the API request: Go to the FastPix API reference and navigate to the Upload media from device endpoint for reference. This lets you create a new direct upload with your desired media settings.
- Receive your upload URL: The API in its response will generate an authenticated URL specifically for your upload. This URL is unique and can be used directly in your client applications.
- Keep track of your upload ID: Along with the URL, you will receive a unique ID for this direct upload. Make sure to save this ID for tracking the upload progress later through the API.
Command line tool:
curl -X POST 'https://v1.fastpix.io/on-demand/uploads' \
--user {Access Token ID}:{Secret Key} \
-H 'Content-Type: application/json' \
-d '{
"corsOrigin": "*",
"pushMediaSettings": {
"accessPolicy": "private",
"startTime": 0,
"endTime": 60,
"metadata": {
"key1": "value1"
},
"createSubtitles": {
"name": "name",
"metadata": {
"key1": "value1"
},
"languageCode": "en-us"
},
"optimizeAudio": true,
"maxResolution": "1080p"
}
}'
Javascript:
<script>
// This endpoint provides you with the signed URL necessary for uploading your video.
const url = 'https://v1.fastpix.io/on-demand/uploads';
// The FastPix Video API employs a token key pair consisting of a Token ID (username) and Token Secret (password) for authentication.
// Generate a new Access Token in the Access Token settings located within your FastPix Organization dashboard.
const username = '';
const password = '';
// Initialize the data object
const data = {
corsOrigin: '*',
newAssetSettings: {
accessPolicy: 'public',
metadata: {
key1: 'value1',
},
generateSubtitles: false,
normalizeAudio: true,
maxResolution: '1080p',
},
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(username + ':' + password
),
},
body: JSON.stringify(data),
}
fetch(url, options)
.then(response => {
if (response.success) {
// You can fetch the signedUrl in the response
}
})
Step 2: Initiate the upload
With the upload URL in hand, you’re ready to upload your media content. In your client application (whether it’s a mobile or web app), use the provided URL to initiate a PUT request. Include the file you want to upload in the request body. The API accepts the media file from the device and uploads it to the FastPix platform.
Step 3: Track your upload
Once uploaded, the media undergoes processing and is assigned a unique ID for tracking. Retain this uploadId for any future operations related to this upload.
Check your FastPix dashboard to confirm successful uploads. You'll see new assets listed with the settings you specified during setup, along with the uploaded video. Alternatively, you can also use the Get Media by ID
endpoint to check the status of the uploaded media asset and see if it has transitioned to a "ready" status for playback.
USING WEBHOOKS
To notify your application about the status of this API request check for the webhooks for Upload related events.
Resumable uploading of large files
When it comes to uploading files, especially large ones like videos, using the right method is crucial for a smooth and efficient experience. This guide explains how to implement resumable uploads effectively.
How resumable uploads work through chunking
Resumable uploads can be effectively handled through a technique called chunking. This method involves breaking down large files into smaller, more manageable pieces, or "chunks." Here's how chunking works:
- Divide the file: Large files are split into smaller, manageable chunks (e.g., 16 MB by default).
- Upload individually: Each chunk is uploaded separately. If a chunk fails, only that specific chunk needs to be re-uploaded.
- Resume capability: If the upload is interrupted, you can resume from the last successfully uploaded chunk instead of starting over.
This approach is important because:
- It reduces the risk: Uploading smaller chunks minimizes the risk of failure. If a chunk fails to upload due to network issues, only that specific chunk needs to be re-uploaded, not the entire file.
- Improves performance: Smaller chunks can be uploaded more quickly and efficiently, especially on slower connections, as they require less time to transfer.
- Easier management: Chunking allows for better tracking of upload progress, making it easier to implement features like pause and resume.
FastPix provides a solution called the "fp-resumable-uploads" library for handling for web uploads.
Overview of fp-resumable-uploads
The fp-resumable-uploads library from FastPix is designed to facilitate efficient file uploads by providing:
- Faster uploads: Large files are divided into smaller chunks, enabling quicker and more efficient uploads.
- Reliable transfers: The library can handle network interruptions, allowing users to resume uploads without starting over.
- Flexibility: Users can pause and resume uploads at their convenience.
Parameters to use
When using the fp-resumable-uploads library, the following parameters are accepted:
- endpoint (mandatory): The URL endpoint where the file will be uploaded.
- file (mandatory): The file object that you want to upload (e.g., a video file).
- chunkSize (optional): chunkSize should be provided in kilobytes (KB). By default, the SDK splits files into chunks of 16 MB. You can customize this by specifying a chunkSize in kilobytes (minimum of 5 MB).
- maxFileSize (optional): This parameter restricts the maximum file size that users can upload. Setting this can help prevent users from attempting to upload excessively large files that may not be manageable.
Installation
To install the fp-resumable-uploads library, use the following command with NPM:
npm install fp-resumable-uploads@latest
Authentication
Before using the SDK, ensure you have a signed URL from the direct uploads API
. This requires creating an Access Token in the FastPix dashboard, which consists of:
- Token ID (username)
- Token Secret (password)
Read the detailed guide on Authentication with Access Tokens.
Below, you'll find React and JavaScript code snippets that show how to integrate the resumable uploads SDK into your project and manage the UI after subscribing to events.
Using in React:
import React, { useState } from 'react';
import { uploadChunk } from 'fp-resumable-uploads';
function Uploads() {
const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState({ status: "", message: "" });
const handleUpload = (video, signedUrl) => {
try {
const fileUpload = uploadChunk.initUpload({
endpoint: signedUrl, // The URL endpoint where the file will be uploaded
file: video, // The file object that you want to upload
chunkSize: 5120, // chunkSize should be provided in kilobytes (KB) and the minimum allowed chunkSize is 5MB.
});
// Event listener for tracking upload progress.
fileUpload.on('progress', event => {
setProgress(event.detail);
});
// Event listener for handling successful upload completion.
fileUpload.on('success', () => {
setStatusMessage({ message: "Upload completed successfully!", status: "success" });
});
// Event listener for handling upload errors.
fileUpload.on('error', event => {
setStatusMessage({ message: event.detail.message, status: "error" });
});
} catch (error) {
setStatusMessage({ message: "An error occurred during upload.", status: "error" });
}
};
const handleUploadProcess = async (videoFile) => {
const file = videoFile.files[0];
if (!file) {
setStatusMessage({ message: "Please select a video to upload.", status: "error" });
return;
}
try {
// This endpoint provides you with the signed URL necessary for uploading your video.
const url = 'https://v1.fastpix.io/on-demand/uploads';
// The FastPix Video API employs a token key pair consisting of a Token ID (username) and Token Secret (password) for authentication.
// Generate a new Access Token in the Access Token settings located within your FastPix Organization dashboard.
const username = '';
const password = '';
// Initialize the data object
const data = {
corsOrigin: '*',
newAssetSettings: {
accessPolicy: 'public',
metadata: {
key1: 'value1',
},
generateSubtitles: false,
normalizeAudio: true,
maxResolution: '1080p',
},
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(username + ':' + password),
},
body: JSON.stringify(data),
}
let getSignedUrl = await fetch(url, options)
let signedUrl = await getSignedUrl.json()
if (signedUrl.success) {
handleUpload(file, signedUrl.data.url)
} else {
console.error(signedUrl.data.error)
}
} catch (error) {
console.error(error)
}
}
return (
<div style={{ textAlign: 'center', width: "100%", border: '1px dashed #0f0f0f' }}>
<h2 style={{ marginBottom: '20px' }}>Fastpix Resumable uploads</h2>
<div style={{ marginTop: "20px" }}>
<input accept="video/*" type="file" onChange={(e) => handleUploadProcess(e.target)} id="videoFile" name="videoFile" style={{ marginBottom: '10px' }} />
</div>
<div style={{ marginTop: "20px" }}>
<p style={{ display: 'block', marginBottom: '10px' }}>Progress: {`${Math.round(progress)}%`} </p
<div style={{ backgroundColor: "#eee", width: "100%", height: "6px", marginTop: "20px" }}>
<div style={{ backgroundColor: "#0CB16D", transition: 'width 0.20s', width: `${progress}%`, height: "6px", marginTop: "20px" }}></div>
</div>
<p style={{ color: `${statusMessage.status === "error" ? 'red' : "green"}` }}>{statusMessage.message}</p>
</div>
</div>
);
}
export default Uploads;
Using in JavaScript:
import { uploadChunk } from 'fp-resumable-uploads';
// Imagine there's an HTML page featuring an input field as follows: <input id="videoFile" type="file" />
const videoFile = document.getElementById('videoFile');
videoFile.onchange = async () => {
try {
// This endpoint provides you with the signed URL necessary for uploading your video.
const url = 'https://v1.fastpix.io/on-demand/uploads';
// The FastPix Video API employs a token key pair consisting of a Token ID (username) and Token Secret (password) for authentication.
// Generate a new Access Token in the Access Token settings located within your FastPix Organization dashboard.
const username = '';
const password = '';
// Initialize the data object
const data = {
corsOrigin: '*',
newAssetSettings: {
accessPolicy: 'public',
metadata: {
key1: 'value1',
},
generateSubtitles: false,
normalizeAudio: true,
maxResolution: '1080p',
},
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(username + ':' + password),
},
body: JSON.stringify(data),
}
let getSignedUrl = await fetch(url, options)
let signedUrl = await getSignedUrl.json()
if (signedUrl.success) {
handleUpload(videoFile.files[0], signedUrl.data.url)
} else {
console.error(signedUrl.data.error)
}
} catch (error) {
console.error(error)
}
}
const handleUpload = (videoFile, signedUrl) => {
const fileUpload = uploadChunk.initUpload({
endpoint: signedUrl, // The URL endpoint where the file will be uploaded
file: videoFile, // The file object that you want to upload
chunkSize: 5120, // chunkSize should be provided in kilobytes (KB) and the minimum allowed chunkSize is 5MB.
});
// Event listener for tracking upload progress.
fileUpload.on('progress', event => {
setProgress(event.detail);
});
// Event listener for handling successful upload completion.
fileUpload.on('success', () => {
setStatusMessage({ message: "Upload completed successfully!", status: "success" });
});
// Event listener for handling upload errors.
fileUpload.on('error', event => {
setStatusMessage({ message: event.detail.message, status: "error" });
});
}
Updated 1 day ago