Vimeo API C# - 上传视频

Vimeo API C# - Uploading a video

我正在遵循 api 关于可续传上传的指南。 我在第 1 步 ("create the video") 后设法得到了回复, 带有 uri 和 upload_link。 关于第二部分,事情还不是很清楚。 它只说明我应该发送哪个 headers,但有两件事我没有得到, 首先 - 我需要把 "upload_link" 放在哪里? 调用应该是这样的:

/我/{upload_link}? (当然我也添加了访问令牌等)

其次,实际文件呢?我想我应该用同样的方法发送它,但是怎么做呢?没有任何消息。

这是 PATCH 请求的代码:

    public string UploadPatch(
string uploadlink,
string method)
{
var headers = new WebHeaderCollection()
{

{ "Tus-Resumable", "1.0.0" },
{ "Upload-Offest", "0" }

};
method = method.ToUpper();


string body = "";
string contentType = "application/offset+octet-stream";

return Helpers.HTTPUpload(uploadlink, method, headers, body, contentType);

}

和 HTTPUpload():

public static string HTTPPatch(string url, string method,
      WebHeaderCollection headers, string payload,
      string contentType)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(url);
        if (Proxy != null) request.Proxy = Proxy;

        request.Headers = headers;
        request.Method = method;
        request.Accept = "application/vnd.vimeo.*+json; version=3.1";
        request.ContentType = contentType;
        request.KeepAlive = false;

        if (!String.IsNullOrWhiteSpace(payload))
        {
            var streamBytes = Helpers.ToByteArray(payload);
            request.ContentLength = streamBytes.Length;
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(streamBytes, 0, streamBytes.Length);
            reqStream.Close();
        }

        HttpWebResponse response = (HttpWebResponse)(request.GetResponse());
        Debug.WriteLine(((HttpWebResponse)response).StatusDescription);

        var dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();

        response.Close();

        Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch");
        Debug.WriteLine(responseFromServer, "HTTPFetch");
        return responseFromServer;
    }

谢谢

upload_link 是您将视频上传到的 URL。换句话说,调用 https://[...].cloud.vimeo.com/upload?[...] URL 而不是用于其他 API 请求的 https://api.vimeo.com 主机。

此外,当您向 cloud.vimeo.com upload_link 提出请求时,请仅提供文档中指定的必需 headers。

https://developer.vimeo.com/api/upload/videos#resumable-approach

代码是VB.Net,不过你可以改成C#

'Imports / use these classes
'Imports System.Net
'Imports Newtonsoft.Json
'Imports System.IO
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
  'Receive the video from File Upload
  If Not IsNothing(fuVideo.PostedFile) Then
    'You will need this for SSL
    System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType.Tls Or (SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12))
    'Path to save the video Save 
    Dim vFilePath As String = Server.MapPath("App_data/Videos")

    Dim vFileNameAndPath As String = vFilePath & "/" & fuVideo.PostedFile.FileName
    'Save Video
    fuVideo.PostedFile.SaveAs(vFileNameAndPath)

    'Get the size
    Dim vSize As String = New FileInfo(vFileNameAndPath).Length()

    'Vimeo URL
    Dim vVimeURL As String = "https://api.vimeo.com/me/videos"

    Dim wc As WebClient = New WebClient()
    wc.Headers.Clear()
    wc.Headers.Add("Authorization", "bearer XXXXXXXXXXXXXXXXX") 'Use your App Code
    wc.Headers.Add("Content-Type", "application/json")
    wc.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4")
    wc.Encoding = System.Text.Encoding.UTF8

    'txtName is a text box, so you can give a Title to the Video
    Dim vData As String = "{ ""upload"": {""approach"": ""tus"",""size"": """ & vSize & """ }, ""name"" : """ & txtName.Text & """ }"

    Dim vimeoTicket = JsonConvert.DeserializeObject(wc.UploadString(vVimeURL, "POST", vData))
    wc.Headers.Clear()
    wc.Headers.Add("Content-Type", "application/offset+octet-stream")
    wc.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4")
    wc.Headers.Add("Tus-Resumable", "1.0.0")
    wc.Headers.Add("Upload-Offset", "0")
    Dim vupload_link As String = vimeoTicket("upload")("upload_link").Value 'Json from Vimeo has the upload_link
    Dim vResponse As Byte() = wc.UploadFile(vupload_link, "PATCH", vFileNameAndPath)
    Response.Write(System.Text.Encoding.Unicode.GetString(vResponse)) ' If everething is ok, vResponse is Nothing
  End If
Catch ex As Exception
  ltrErro.Text = "Error"
End Try
End Sub

为此可以查看下面的示例代码:-

我也在 https://github.com/mfilippov/vimeo-dot-net 使用 nuget 库 vimeo-dot-net,它有一个围绕上传、删除等构建的包装器。

       public ActionResult UploadChapterVideoVimeo(HttpPostedFileBase file, string productID = "")
    {
        if (file != null){      
                          var authCheck = Task.Run(async () => await vimeoClient.GetAccountInformationAsync()).Result;
                    if (authCheck.Name != null)
                    {
                        
                        BinaryContent binaryContent = new BinaryContent(file.InputStream, file.ContentType);
                        int chunkSize = 0;
                        int contenetLength = file.ContentLength;
                        int temp1 = contenetLength / 1024;
                        if (temp1 > 1)
                        {
                            chunkSize = temp1 / 1024;
                            chunkSize = chunkSize * 1048576;
                        }
                        else
                        { chunkSize = chunkSize * 1048576; }
                        binaryContent.OriginalFileName = file.FileName;
                        var d = Task.Run(async () => await vimeoClient.UploadEntireFileAsync(binaryContent, chunkSize, null)).Result;
                        vmodel.chapter_vimeo_url = "VIMEO-" + d.ClipUri;
                    }

                    return RedirectToAction("ProductBuilder", "Products", new { productId = EncryptedProductID, message = "Successfully Uploaded video", type = 1 });
                }
            }
            catch (Exception exc)
            {
                return RedirectToAction("ProductBuilder", "Products", new { productId = EncryptedProductID, message = "Failed to Uploaded video " + exc.Message, type = 0 });
            }
        }
        return null;        }