当前位置: 首页 > 知识库问答 >
问题:

YouTube API v3,C#MVC-使用OAuth将视频上传到我的频道

薄哲
2023-03-14

我在MVC Web应用程序中使用YouTubeAPI V3。目的是让我的Web用户使用MY OAuth凭据将视频上传到MYYouTube频道。在用户将他们的视频上传到我的Web服务器后,我需要在我的Web服务器和YouTube之间自动上传,无需我自己的用户干预。

我的(初稿)代码如下。我的问题是:

> < li>

更新-已在下面解决。每当我试图删除一个视频,我得到一个“未经授权”的错误。当我检查令牌的范围时,它只有“YoutubeUpload”而没有“Youtube”。有什么方法可以解决这个问题吗?

我创建了一个类型为“Other”的OAuth客户端凭据并导出了JSON(我指定了“Other”,而不是“Web应用程序”-是否正确?)https://console.developers.google.com/apis/credentials

当我尝试上传视频时,我会被重定向到“授权应用程序”,上面写着“我的公司想访问您的YouTube频道”问题是,我不想访问任何人的频道。我只是希望他们能够上传到我的频道。这可能吗,如果可能,怎么做?

    public async Task<string> UploadVideoToYouTube(Stream filestream)
    {
        UserCredential credential;

        string cs = HttpContext.Current.Server.MapPath("~/client_secrets.json");

        using (var stream = new FileStream(cs, FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                // This OAuth 2.0 access scope allows an application to upload files to the
                // authenticated user's YouTube channel, but doesn't allow other types of access.
                new[] { YouTubeService.Scope.Youtube,
                    YouTubeService.Scope.YoutubeUpload },
                "user",
                CancellationToken.None
            );
        }

       //check scope with this URL
        //https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={ACCESS-TOKEN}
        // This bit checks if the token is out of date, 
        // and refreshes the access token using the refresh token.
        if (credential.Token.IsExpired(SystemClock.Default))
        {
            if (!await credential.RefreshTokenAsync(CancellationToken.None))
            {
                Console.WriteLine("No valid refresh token.");
            }
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });

        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = "Default Video Title";
        video.Snippet.Description = "Default Video Description";
        video.Snippet.Tags = new string[] { "tag1", "tag2" };
        //https://gist.github.com/dgp/1b24bf2961521bd75d6c
        //26 - How-to & Style
        video.Snippet.CategoryId = "26"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "private"; // "unlisted" or "private" or "public"

        var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", filestream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        await videosInsertRequest.UploadAsync();

        return videosInsertRequest.ResponseBody.Id;
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        //http://www.youtube.com/watch?v={VIDEO-ID}
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);

    }

    public async Task DeleteVideoFromYouTube(string id)
    {
        UserCredential credential;

        string cs = HttpContext.Current.Server.MapPath("~/client_secrets.json");

        using (var stream = new FileStream(cs, FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                // This OAuth 2.0 access scope allows an application to upload files to the
                // authenticated user's YouTube channel, but doesn't allow other types of access.
                new[] {   YouTubeService.Scope.Youtube,                    
                YouTubeService.Scope.YoutubeUpload  },
                "user",
                CancellationToken.None
            );
        }

        // This bit checks if the token is out of date, 
        // and refreshes the access token using the refresh token.
        if (credential.Token.IsExpired(SystemClock.Default))
        {
            if (!await credential.RefreshTokenAsync(CancellationToken.None))
            {
                Console.WriteLine("No valid refresh token.");
            }
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
        });

        var videosDeleteRequest = youtubeService.Videos.Delete(id);
        await videosDeleteRequest.ExecuteAsync();


    }

    void videosInsertRequest_ProgressChanged(IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                break;

            case UploadStatus.Failed:
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
    }

更新第一个问题的解决方案是到这里:https://myaccount.google.com/permissions,删除授权的YouTube应用程序。它必须在没有YouTubeService的情况下被授权。范围Youtube范围。

然而,当我删除该帐户并再次运行web应用程序时,它提示我再次使用OAuth进行身份验证。我不想让它这样做。我希望它自动以我的身份进行身份验证(针对所有用户)。这是我尚未回答的第二个问题。。。。

共有2个答案

端木安国
2023-03-14

这是在YouTube上上传视频的示例代码

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

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

namespace Google.Apis.YouTube.Samples
{
  /// <summary>
  /// YouTube Data API v3 sample: upload a video.
  /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
  /// See https://developers.google.com/api-client-library/dotnet/get_started
  /// </summary>
  internal class UploadVideo
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Upload Video");
      Console.WriteLine("==============================");

      try
      {
        new UploadVideo().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
      UserCredential credential;
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
      {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            // This OAuth 2.0 access scope allows an application to upload files to the
            // authenticated user's YouTube channel, but doesn't allow other types of access.
            new[] { YouTubeService.Scope.YoutubeUpload },
            "user",
            CancellationToken.None
        );
      }

      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
      });

      var video = new Video();
      video.Snippet = new VideoSnippet();
      video.Snippet.Title = "Default Video Title";
      video.Snippet.Description = "Default Video Description";
      video.Snippet.Tags = new string[] { "tag1", "tag2" };
      video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
      video.Status = new VideoStatus();
      video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
      var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

      using (var fileStream = new FileStream(filePath, FileMode.Open))
      {
        var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        await videosInsertRequest.UploadAsync();
      }
    }

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

        case UploadStatus.Failed:
          Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
          break;
      }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
      Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }
  }
}
邹嘉致
2023-03-14

关键在这部分代码中:

credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        // This OAuth 2.0 access scope allows an application to upload files to the
        // authenticated user's YouTube channel, but doesn't allow other types of access.
        new[] { YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None
    );

您必须指定正确的用户名,而不仅仅是“用户”

 类似资料:
  • 我试图使用API接口将视频上传到S3存储桶,我遵循了预签名的URL过程,下面是我的lambda函数,它返回预签名的URL(它正确地返回了预签名的URL,看起来): 当我尝试上传一个像这样卷曲的mp4视频时,例如: curl-X PUT-F'data=@ch01_00000100055009702.mp4'https://redacted-bucket-instance.s3.amazonaws.c

  • 接口说明 上传视频文件 API地址 POST /api/marker/1.0.0/uploadVideo 是否需要登录 是 请求字段说明 参数 类型 请求类型 是否必须 说明 dataGuid string form 是 场景GUID file string form 是 视频文件 响应字段说明 参数 类型 说明 mp4UploadPath String 视频文件上传地址 响应成功示例 { "

  • 用户通过视频上传、管理视频、获取代码,实现本地视频在制定网站播放。 2.1视频上传 进入视频页面,点击上传视频 按钮,在弹出的页面点击添加视频 : 1)选择视频“分类”,添加视频“标签”(选填); 2)点击【添加视频】或者【选择文件并上传】按钮选择本地一个或多个视频,点击确认即开始视频上传;或者在本地选择一个或多个视频,将视频拖拽到视频上传区,即可进行视频上传; 3)上传过程中点击视频上传或者取消

  • 我正在尝试通过YouTube数据API v3将视频上传到多个频道。 当我将视频上传到主默认频道时,我可以正确地做到这一点,但是当我们尝试将它们上传到同一Youtube帐户的另一个频道时,却无法做到(因此OAuth2凭据应该是有效的)。 根据文档,在调用endpoint时,我必须将以下参数传递给API:onBehalfOfContentOwnerChannel和onBehalfOfContentOw

  • Spark API 中所有的 Flash 接口需要 Flash 插件的版本在 10.1 以上才有效,使用前请确保 Flash 插件版本符合要求。 在上传视频的过程中,不用与 Spark 平台进行 HTTP 通信,使用 JavaScript 和 Spark 平台提供的 Flash 进行交互即可完成。关于如何在网页中嵌入 Flash 以及如何和 Flash 进行交互,请参阅附录 2。上传接口用到的所有

  • 我正试图用PHP上传一个视频到Youtube。我用的是Youtube API v3,我用的是最新的谷歌API PHP客户端库的源代码。< br >我使用< br > https://code.google.com/p/google-api-php-client/上给出的示例代码来执行身份验证。身份验证顺利通过,但当我尝试上传视频时,我得到< code > Google _ service exce