Vimeo API C# - 上传视频

时间:2018-02-21 16:15:37

标签: vimeo-api

我正在关注有关可恢复上传的api指南。 我设法在第1步(“创建视频”)后得到回复, 使用uri和upload_link。 关于第二部分,事情并不那么明确。 它只说我应该发送哪些标题,但有两件事我不知道, 首先 - 我需要在哪里放“upload_link”? 电话会是这样的:

/ ME / {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;
    }

由于

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

代码是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

答案 2 :(得分:0)

为此,请查看下面的示例代码:-

我也在https://github.com/aarav123-android/order_vegetables上使用了一个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;        }