How to upload files to Yammer using JS SDK

Unfortunately at the time of this post the documentation on the yammer developer site is very poor, while it has the REST API reference, the JS SDK does not have many examples and for some folks out there taking this kind of documentation and translating into code might be difficult.

When giving some classes about Office 365 development, one of the modules was yammer developement and one of the questions from the students was how to upload files.

The code below shows how to do it using the messages.json endpoint, this is the simplest example possible, as it will post the file to the All Company feed, for more complex examples, the data json variable needs to have more parameters like groupid, etc.

function postActivity() {

    var m_data = new FormData();
    m_data.append('body', 'hola mundoxyz');
    m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
    m_data.append('direct_to_user_ids', []);

                // yam.request({
                url: "messages.json", //this is one of many REST endpoints that are available
                contentType: "multipart/form-data",
                method: "POST",
                data: m_data,
                processData: false,
                contentType: false,
                success: function (activity) { //print message response information to the console
                    console.log("Activity request was successful.");
                    $('#authResult').html('User Result:<br/>');
                    for (var field in activity) {
                        $('#authResult').append(' ' + field + ': ' +
                            escape(activity[field]) + '<br/>');
                error: function (activity) {
                    console.error("There was an error with the request.");

The really complex part and what the documentation is missing is the headers, which the documentation doesnt mention:

  processData: false,
                contentType: false,

and the content type

 contentType: "multipart/form-data",