javascriptapiyammer

Uploading a file via Yammer API


I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:

TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.

function post() {
    yam.getLoginStatus( function(response) {
        if (response.authResponse) {

            yam.request(
              { url: "https://api.yammer.com/api/v1/messages.json" //note:  the endpoint is api.yammer...
              , method: "POST"
              , data: {
                "body" : document.getElementById("post_body").value,
                "group_id" : document.getElementById("group_id").value
                ,"attachment1" : document.getElementById("attachment")
              }
              , success: function (msg) {
                    alert("Post was Successful!: " + msg.messages[0].id); //id of new message
              }
              , error: function (msg) { alert("Post was Unsuccessful..." + msg); }
              }
            );
        } else {
            yam.login( function (response) {
               //nothing
            });
        }
    });
}

Solution

  • yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:

            var data = new FormData();
    
            data.append('body', document.getElementById("post_body").value);
            data.append('group_id', document.getElementById("group_id").value);
    
    
            data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
    
    
            $.ajax({
                url: "https://api.yammer.com/api/v1/messages.json",
                data: data,
                beforeSend: function (xhr) {
                    // set authorization header
                    xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
                },
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function (data) {
                    console.log("ajax post success.");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("There was an error with the request.");
                }
            });
    

    Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.