Uploading a file via Yammer API

一世执手 提交于 2019-12-04 18:50:33

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.

It works for me:

function postAttach() {
	var msg = $('#attach_body').val();
	
	var m_data = new FormData();
	m_data.append('body', msg);
	m_data.append('group_id', 6194208);
	m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);

	yam.platform.request({
		
		url: "messages.json",     
		contentType: "multipart/form-data",
		data: m_data,
		processData: false,
		contentType: false,
		type: 'POST',
		dataType: 'json',
		success: function (user) { 
			alert("The request was successful.");
		},
		error: function (user) {console.log(user);
			alert("There was an error with the request.");
		}
	});
}
 <div name="postYammer">
    	<input type="text" name="body" value="" id="attach_body" />
    	<input type="file" name="attachment1"  id="attach_img"/>
    	<button onclick="postAttach()" type="button">Post</button>
    </div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!