fastevo-mp2-uploader-lib

1.0.3 • Public • Published

fastevo-mp2-uploader-lib

npm version License: MIT Node.js Version

A powerful and efficient JavaScript library for uploading content to the Fastevo MP2 media protection platform. This library provides a clean interface for both single-part and multipart uploads with built-in pause, resume, and abort capabilities.

Features

  • Robust Upload Support: Handles both standard and multipart uploads to Fastevo's media protection platform
  • Pause/Resume Functionality: Interrupt and continue uploads as needed
  • Progress Tracking: Real-time upload progress monitoring
  • Error Handling: Comprehensive error reporting and management
  • Event-Based Architecture: Subscribe to various upload lifecycle events
  • Automatic Termination: One-time use instances with proper cleanup
  • Authentication: Simple token-based authentication

Installation

npm install fastevo-mp2-uploader-lib

Quick Start

import FastevoUploader from 'fastevo-mp2-uploader-lib';

// Initialize with your upload token
const uploader = new FastevoUploader('your-upload-token');

// Listen for upload events
uploader.on('uploadProgress', (file, progress) => {
  console.log(`Upload progress: ${progress.bytesUploaded} / ${progress.bytesTotal}`);
  const percentage = Math.floor((progress.bytesUploaded / progress.bytesTotal) * 100);
  console.log(`${percentage}% completed`);
});

uploader.on('uploadComplete', (file, result) => {
  console.log('Upload completed successfully!', result);
});

uploader.on('uploadError', (file, error) => {
  console.error('Upload failed:', error);
});

// Start the upload with a file
// Note: The file must be a File object (from an input element or drag-and-drop)
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', async () => {
  const file = fileInput.files[0];
  if (file) {
    try {
      await uploader.start(file);
      // The uploader is automatically terminated after completion
    } catch (error) {
      console.error('Upload process error:', error);
    }
  }
});

// Optional: Pause button
document.getElementById('pause-button').addEventListener('click', () => {
  uploader.pause();
});

// Optional: Resume button
document.getElementById('resume-button').addEventListener('click', () => {
  uploader.resume();
});

// Optional: Abort button
document.getElementById('abort-button').addEventListener('click', () => {
  uploader.abort();
});

API Reference

Constructor

const uploader = new FastevoUploader(uploadToken, options);

Parameters

  • uploadToken (string, required): The authentication token for Fastevo API
  • options (object, optional):

Methods

start(file)

Initiates the upload process for a file.

await uploader.start(file);
  • file (File, required): A File object to upload
  • Returns: Promise that resolves with the upload result

pause()

Pauses the current upload.

uploader.pause();

resume()

Resumes a paused upload.

uploader.resume();

abort()

Aborts the upload and terminates the uploader instance.

uploader.abort();

Events

The uploader extends EventEmitter and emits the following events:

uploadProgress

Emitted during the upload process with progress information.

uploader.on('uploadProgress', (file, progress) => {
  // progress.bytesUploaded: Number of bytes uploaded
  // progress.bytesTotal: Total number of bytes to upload
});

uploadComplete

Emitted when the upload completes successfully.

uploader.on('uploadComplete', (file, result) => {
  // result: Upload result data
});

uploadError

Emitted when an error occurs during upload.

uploader.on('uploadError', (file, error) => {
  // error: Error object with details
});

uploadPaused

Emitted when the upload is paused.

uploader.on('uploadPaused', () => {
  // Upload has been paused
});

uploadResumed

Emitted when the upload is resumed.

uploader.on('uploadResumed', () => {
  // Upload has been resumed
});

Important Implementation Notes

  1. One-Time Use: Each uploader instance is designed for a single upload and is automatically terminated upon completion, error, or abort. Create a new instance for each upload.

  2. Token Sanitization: The library automatically sanitizes the upload token to ensure it's valid for HTTP headers.

  3. File Restrictions: The uploader is configured to accept only one file at a time.

  4. Multipart vs. Single Upload: The library automatically determines whether to use multipart or single upload based on the server's response to the start request.

  5. Concurrent Chunk Uploads: In multipart mode, up to 5 chunks are uploaded concurrently for optimal performance.

Error Handling

The library provides detailed error information through the uploadError event and thrown exceptions. Common error scenarios include:

  • Authentication failures (invalid upload token)
  • Network connectivity issues
  • Server-side errors during upload initialization or completion
  • File validation errors
  • User-initiated aborts

Advanced Usage

Custom API URL

You can specify a custom API endpoint for development or testing:

const uploader = new FastevoUploader('your-upload-token', {
  apiUrlBase: 'https://staging-api.example.com'
});

Handling Upload Progress

For a more detailed progress handling implementation:

uploader.on('uploadProgress', (file, progress) => {
  const percentage = Math.floor((progress.bytesUploaded / progress.bytesTotal) * 100);
  
  // Update UI with percentage
  document.getElementById('progress-bar').value = percentage;
  document.getElementById('progress-text').textContent = `${percentage}%`;
  
  // Display transfer speed
  const currentTime = Date.now();
  if (window.lastProgressTime) {
    const timeDiff = (currentTime - window.lastProgressTime) / 1000; // in seconds
    const bytesDiff = progress.bytesUploaded - window.lastBytesUploaded;
    const speedMbps = ((bytesDiff / 1024 / 1024) / timeDiff).toFixed(2);
    document.getElementById('speed').textContent = `${speedMbps} MB/s`;
  }
  
  window.lastProgressTime = currentTime;
  window.lastBytesUploaded = progress.bytesUploaded;
});

Browser Compatibility

This library supports all modern browsers and requires ES6 support. The minimum supported browsers are:

  • Chrome 61+
  • Firefox 60+
  • Safari 11+
  • Edge 16+

Troubleshooting

Common Issues

  1. Upload Fails to Start

    • Ensure your upload token is valid and has not expired
    • Check network connectivity to the API endpoint
  2. Paused Upload Cannot Resume

    • Some upload sessions may expire on the server after a certain period
    • Ensure your application has not lost network connectivity
  3. "Already Terminated" Error

    • Remember that each uploader instance is for one-time use only
    • Create a new instance for each new upload

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For issues, feature requests, or questions, please submit a GitHub issue at: https://github.com/Fastevo/mp2-uploader-lib/issues

Package Sidebar

Install

npm i fastevo-mp2-uploader-lib

Weekly Downloads

8

Version

1.0.3

License

MIT

Unpacked Size

19.6 kB

Total Files

4

Last publish

Collaborators

  • visiontsnpm