使用YouTube API和CORS上传视频

时间:2013-04-17 14:25:36

标签: asp.net ajax youtube-api

我正在尝试允许访问我们网站的访问者将视频上传到我们的YouTube频道。因此,我不想使用OAuth处理身份验证,否则我将需要在任何地方分发我们的用户名和密码。我不想直接上传,因为我不想自己主持视频。

所以,我有一个表单收集面板中的一些细节,该按钮强制回发到我创建Video对象后面的代码并获取FormUploadToken。然后,我使用该信息创建一个发布到页面上的Literal中的信息。

选择文件,然后单击上传按钮。立即触发中止事件,但没有理由说明原因。

任何想法?非常感谢帮助:

         <form id="Form1" runat="server">
            <asp:Literal ID="Literal1" runat="server"></asp:Literal>
            <br />
            <dx:ASPxPanel ID="ASPxPanel1" runat="server" Width="200px">
            <PanelCollection>
                <dx:PanelContent ID="PanelContent1" runat="server" SupportsDisabledAttribute="True">
                    <dx:ASPxLabel ID="ASPxLabel1" runat="server" Text="Name"> </dx:ASPxLabel>
                    <dx:ASPxTextBox ID="NameTextBox" runat="server" Width="170px" Text="Simon"> </dx:ASPxTextBox>
                    <dx:ASPxLabel ID="ASPxLabel2" runat="server" Text="Email address"> </dx:ASPxLabel>
                    <dx:ASPxTextBox ID="EmailTextBox" runat="server" Width="170px" Text="info@example.com"> </dx:ASPxTextBox>
                    <dx:ASPxLabel ID="ASPxLabel3" runat="server" Text="Video title"> </dx:ASPxLabel> 
                    <dx:ASPxTextBox ID="VideoTitleTextBox" runat="server" Width="170px" Text="My new video title"> </dx:ASPxTextBox>
                    <dx:ASPxLabel ID="ASPxLabel4" runat="server" Text="Keywords - comma separated"> </dx:ASPxLabel>
                    <dx:ASPxTextBox ID="KeywordsTextBox" runat="server" Width="170px" Text="India, Kochin"> </dx:ASPxTextBox>
                    <dx:ASPxLabel ID="ASPxLabel5" runat="server" Text="Video description"> </dx:ASPxLabel>
                    <dx:ASPxTextBox ID="VideoDescriptionTextBox" runat="server" Width="170px" Text="An amazing description that makes a lot of sense"> </dx:ASPxTextBox>

                    <dx:ASPxButton ID="ASPxButton1" runat="server" onclick="VideoUploadBttn_Click" Text="ASPxButton"> </dx:ASPxButton>

                </dx:PanelContent>
            </PanelCollection>
            </dx:ASPxPanel>
        </form>

        <dx:ASPxPanel ID="ASPxPanel2" runat="server" Width="200px" Visible="False">
        <PanelCollection>
        <dx:PanelContent ID="PanelContent2" runat="server" SupportsDisabledAttribute="True">
            <asp:Literal ID="Literal2" runat="server"></asp:Literal>
        </dx:PanelContent>
        </PanelCollection>
        </dx:ASPxPanel>

<script type="text/javascript">
    function fileSelected() {
        var file = document.getElementById('fileToUpload').files[0];
        if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024)
                fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
                fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

            document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
            document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
            document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
        }
    }

    function uploadFile() {
        var fd = new FormData();
        fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);

        xhr.open("POST", document.UploadForm.action);
        console.log('action url: ' + document.UploadForm.action);

        xhr.send(fd);
    }

    function uploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
        }
        else {
            document.getElementById('progressNumber').innerHTML = 'unable to compute';
        }
    }

    function uploadComplete(evt) {
        /* This event is raised when the server send back a response */
        alert(evt.target.responseText);
    }

    function uploadFailed(evt) {
        alert("There was an error attempting to upload the file.");
    }

    function uploadCanceled(evt) {
        alert("The upload has been canceled by the user or the browser dropped the connection.");
        console.log(evt);
    }
</script>

然后背后的代码如下:

protected void VideoUploadBttn_Click(object sender, EventArgs e)
{
    Video newVideo = new Video();

    newVideo.Title = VideoTitleTextBox.Text;
    newVideo.Tags.Add(new MediaCategory("Travel", YouTubeNameTable.CategorySchema));
    newVideo.Keywords = KeywordsTextBox.Text;
    newVideo.Description = VideoDescriptionTextBox.Text;
    newVideo.YouTubeEntry.Private = false;
    newVideo.Keywords = "Travel";
    newVideo.Tags.Add(new MediaCategory("Motorbike", YouTubeNameTable.DeveloperTagSchema));

    // alternatively, you could just specify a descriptive string
    // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
    YouTubeRequestSettings settings = new YouTubeRequestSettings(_AppName, _APIKey, _Username, _Password);
    YouTubeRequest request = new YouTubeRequest(settings);

    FormUploadToken uploadToken = request.CreateFormUploadToken(newVideo);
    string actionUrl = uploadToken.Url;
    string token = uploadToken.Token;

    StringBuilder sb = new StringBuilder();
    string url = String.Format("{0}?nexturl={1}", actionUrl, System.Web.HttpUtility.UrlEncode("http://bbc.co.uk"));

    sb.AppendFormat("<form name=\"UploadForm\" action=\"{0}\" method =\"post\" enctype=\"multipart/form-data\" >", url);
    sb.Append("<input type=\"file\" name=\"file\" id=\"fileToUpload\" onchange=\"fileSelected();\" />");
    sb.AppendFormat("<input type=\"hidden\" name=\"token\" value=\"{0}\"/>", token);
    sb.Append("<div id=\"fileName\"></div>");
    sb.Append("<div id=\"fileSize\"></div>");
    sb.Append("<div id=\"fileType\"></div>");

    sb.Append("<input type=\"submit\" value=\"Upload\" onclick=\"uploadFile()\" />");
    sb.Append("<div id=\"progressNumber\"></div>");

    sb.Append("</form>");

    Literal2.Text = sb.ToString();

    ASPxPanel1.Visible = false;
    ASPxPanel2.Visible = true;
}

1 个答案:

答案 0 :(得分:0)

发现它!它与我们使用ClientLogin或CORS的事实无关,而且与表单按钮上的输入类型是提交类型而不是按钮的事实有关。

简单地改变它是一种享受。添加AuthSubUtil非常简单,因此将视频上传到个人帐户,然后我们将它们链接到我们的播放列表。

新问题似乎与nextUrl参数有关 - 请参阅此处: Youtube API, nexturl and XMLHttpRequest