youtube-apicorsxmlhttprequest-level2

Upload a video on Youtube by means of XHR2


My customer wants to show progress dialog just as user is uploading video on Youtube.

I write something like:

    element = document.forms.uploadNewVideoForm.file;

    var fd = new FormData();
    console.log(element.files);
    fd.append('token', $scope.uploadData.token);
    fd.append('file', element.files[0]);

    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", $scope.uploadProgress, false);
    xhr.addEventListener("load", $scope.uploadComplete, false);
    xhr.addEventListener("error", $scope.uploadComplete, false);
    xhr.addEventListener("abort", $scope.uploadComplete, false);
    xhr.open("POST", $scope.uploadData.uploadUrl + '?nexturl=' + encodeURIComponent('http://local.app.com:8000/OK'));

    xhr.onreadystatechange = function ( response ) {};
    xhr.send(fd);

This code start perfectly, but it fails when Youtube redirects to callback URL.

POST http://uploads.gdata.youtube.com/action/FormDataUpload/<token here>?nexturl=http%3A%2F%2Flocal.app.com%3A8000%2FOK

302 Moved Temporarily 
Location: http://local.app.com:8000/OK

Here request interrupts and the error callback is invoked.


Solution

  • Take a look at the following sample (source code). It breaks the upload into two parts:

    1. A CORS request to upload the metadata.
    2. A form POST to upload the actual video.

    Unfortunately the upload page doesn't support CORS yet, so this is the best you can do.