Aa Yy
Aa Yy

Reputation: 1742

Vimeo API C# - Uploading a video

I'm following the api's guide about resumable uploads. I managed to get a response after step 1 ("create the video"), with a uri and a upload_link. About the second part, things are not as clear. It only says which headers should I sent, but there are two things I don't get, first - where do I need to put the "upload_link"? Should the call be like this:

/me/{upload_link}? (of course im also adding the access token, etc)

second, what about the actual file? I guess i should send it in the same method, but how? No word about it.

This is the code for the PATCH request:

    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);

}

And 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;
    }

Thanks

Upvotes: 0

Views: 6370

Answers (3)

Dheeraj Singh
Dheeraj Singh

Reputation: 109

for this may look at the sample code below:-

I am using a nuget library vimeo-dot-net also at https://github.com/mfilippov/vimeo-dot-net, this has a wrapper built around upload, delete etc.

       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;        }

Upvotes: 1

The code is VB.Net, but you can change to 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

Upvotes: 0

Tommy Penner
Tommy Penner

Reputation: 3018

The upload_link is the URL where you upload the video to. In other words, make your call to the https://[...].cloud.vimeo.com/upload?[...] URL instead of the https://api.vimeo.com host that is used for other API requests.

Additionally, when you make a request to that cloud.vimeo.com upload_link, only provide the required headers as specified in the documentation.

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

Upvotes: 2

Related Questions