Skip to content

Instantly share code, notes, and snippets.

@jakecausier
Created March 15, 2020 16:28
Show Gist options
  • Save jakecausier/21730a4edf3251548584049ecf3fb073 to your computer and use it in GitHub Desktop.
Save jakecausier/21730a4edf3251548584049ecf3fb073 to your computer and use it in GitHub Desktop.
CloudFlare Stream upload using tus-js-client
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();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment