Skip to content

Instantly share code, notes, and snippets.

@jakecausier
Created March 15, 2020 16:28
Show Gist options
  • Select an option

  • Save jakecausier/21730a4edf3251548584049ecf3fb073 to your computer and use it in GitHub Desktop.

Select an option

Save jakecausier/21730a4edf3251548584049ecf3fb073 to your computer and use it in GitHub Desktop.

Revisions

  1. Jake Causier renamed this gist Mar 15, 2020. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Jake Causier created this gist Mar 15, 2020.
    57 changes: 57 additions & 0 deletions upload.ks
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    const tus = require("tus-js-client")

    document.getElementById('tus-video-input').addEventListener('change', function(e) {

    var file = e.target.files[0]
    var xhr = new XMLHttpRequest()

    console.log(file);

    xhr.open('POST', `${videoUploaderConfig.CloudflareEndpoint}/accounts/${videoUploaderConfig.CloudflareApiAccount}/stream`, true)
    xhr.setRequestHeader('Authorization', `Bearer ${videoUploaderConfig.CloudflareApiKey}`)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.setRequestHeader('Tus-Resumable', '1.0.0')
    xhr.setRequestHeader('Upload-Length', file.size)

    xhr.onload = function(res) {
    if (res.target.status < 400) {

    console.log('Got good response from Cloudflare!')
    var cloudflareUploadLocation = xhr.getResponseHeader('location')

    var upload = new tus.Upload(file, {
    uploadUrl: cloudflareUploadLocation,
    retryDelays: [0, 3000, 5000, 10000, 20000],
    metadata: {
    filename: file.name,
    filetype: file.type
    },
    headers: {
    'Authorization': `Bearer ${videoUploaderConfig.CloudflareApiKey}`,
    },
    onError: function(error) {
    console.log("Failed because: " + error)
    },
    onProgress: function(bytesUploaded, bytesTotal) {
    var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
    console.log(bytesUploaded, bytesTotal, percentage + "%")
    },
    onSuccess: function() {
    console.log('Upload complete! Response meta:', upload)
    document.getElementById('video_id').value = upload.url
    }
    })

    console.log('Attempting upload...')
    upload.start()

    } else {

    console.log('Bad response from Cloudflare')

    }

    }
    xhr.send();

    })