首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >YouTube API V3上传视频引发异常

YouTube API V3上传视频引发异常
EN

Stack Overflow用户
提问于 2014-09-10 10:26:07
回答 1查看 1.9K关注 0票数 1

我正在使用C#使用Web应用程序,用户将浏览视频文件,web应用程序将通过YouTube API V3上传到YouTube。我收到错误了。请告诉我哪里做错了?

错误: System.ArgumentNullException:值不能为空。参数名称: Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task任务中的baseUri )在Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task任务上的baseUri)在c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis\ApisMedia\Upload\ResumableUpload.cs:line 459中的Google.Apis.Upload.ResumableUpload1.d__e.MoveNext()上的Microsoft.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()

我遵循以下几点。

  1. 为for应用程序创建ClientID,并从API访问页面下载client_secrets.json文件。
  2. 使用https://developers.google.com/youtube/v3/docs/videos/insert#examples中提供的https://developers.google.com/youtube/v3/docs/videos/insert#examples示例代码也引用了来自样本/dotnet的相同代码
  3. 我的应用程序获得了YouTube API的授权。
  4. 当上传视频文件,我得到以下错误。

我把代码贴在下面,供你参考。

/* TestFileUploader.aspx */

代码语言:javascript
复制
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestFileUploader.aspx.cs" Inherits="TestFileUploader" Async="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <form id="qaform" runat="server">
        <div>
            <p>
                <asp:FileUpload runat="server" ID="FileUpload1" onchange="AddEventChoosePicture(this,'FileUpload1')"
                    Style="width: 100%;" />
            </p>
            <p>
                <asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="Submit" />
            </p>
        </div>
    </form>
</body>
</html>

/* TestFileUploader.aspx.cs */

代码语言:javascript
复制
using System;
using System.Web;
using System.IO;
using QA.credential;

using Google.Apis.Auth.OAuth2;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using Google.Apis.YouTube.v3.Data;
using Google.Apis.Upload;

public partial class TestFileUploader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void submit_Click(object sender, EventArgs e)
    {
        try
        {
            if (FileUpload1.HasFile)
            {
                String FileUpload1_Ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
                UploadVideos(FileUpload1.FileContent, FileUpload1.PostedFile.ContentType);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

    private async void UploadVideos(Stream uploadedStream, String contenttype)
    {
        try
        {
            UserCredential credential;
            String clientsecretkeypath = HttpContext.Current.Server.MapPath("~/client_secrets.json");
            using (var stream = new FileStream(clientsecretkeypath, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user", System.Threading.CancellationToken.None);
            }

            // Create the service.
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                //ApiKey = "AIzaSyAFxuAA4r4pf6VX75zEwCrIh5z4QkzOZ6M",
                HttpClientInitializer = credential,
                ApplicationName = PhotoandVideoupload.applicationname
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "My Test Movie";
            video.Snippet.Description = "My description";
            video.Snippet.Tags = new string[] { "Autos" };
            video.Snippet.CategoryId = "2";
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted";

            // Using snippet,status below throws 401(UnAuthorized issue).
            // Using snippet alone throws 404(Bad Request).
            //In both case, Null Exception throws for parameter baseURI.
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            Google.Apis.Upload.IUploadProgress progress = await videosInsertRequest.UploadAsync();

            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Response.Write(String.Format("{0} bytes sent.", progress.BytesSent));
                    break;

                case UploadStatus.Failed:
                    Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
                    Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
                    break;
            }


            // Also tried to read file from server path instead of uploading via fileupload control.
            /*
            using (var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/1.mp4"), FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, contenttype);
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
            */

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + " " + ex.StackTrace);
        }
        finally
        {
        }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                Response.Write(String.Format("{0} bytes sent.", progress.BytesSent));
                break;

            case UploadStatus.Failed:
                Response.Write(String.Format("{0}<br/>", progress.Exception.Message));
                Response.Write(String.Format("{0}<br/>", progress.Exception.StackTrace));
                break;
        }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        Response.Write(String.Format("Video id '{0}' was successfully uploaded.", video.Id));
    }

}

请告诉我哪里做错了?

谢谢,

EN

回答 1

Stack Overflow用户

发布于 2014-09-11 22:18:52

您可以尝试以下更改:

发自:

代码语言:javascript
复制
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet", uploadedStream, contenttype);

至:

代码语言:javascript
复制
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", uploadedStream, contenttype);

另外,内容类型中的内容是什么?我使用视频/*作为视频上传的内容类型。

状态代码401错误可能是因为YouTube API尚未被授权。检查您是否已授权YouTube API用于您的凭据。转到Google开发者控制台并单击您的项目名称。然后单击左侧导航菜单中的“API”。检查YouTube Data v3是否已打开。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25763038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档