How to upload files on Yammer API via the Azure Upload Small File API

眉间皱痕 提交于 2021-02-15 07:13:18

问题


How to upload an attachment along with a Yammer message?

Any legacy method through attachment1 etc. fields of the /messages.json endpoint won't work anymore.

The new method is not so well documented: https://developer.yammer.com/docs/upload-files-into-yammer-groups

I'm giving here an example in PHP below, but you can do the same in any language.


回答1:


You have to do it in two part

  1. First upload the picture to https://filesng.yammer.com/v4/uploadSmallFile and get the picture's id.
  2. Send your message as usual to https://www.yammer.com/api/v1/messages.json along with the freshly got picture id.

Note: I will use here the Guzzle library for the REST calls.

1. Send the picture to the Azure cloud

protected function yammerFileUpload(string $file, string $filename): int
{
    $multipart = [
        [
            'name'      => 'network_id',
            'contents'  => $this->networkId,
        ],
        [
            'name'      => 'group_id',
            'contents'  => $this->groupId,
        ],
        [
            'name'      => 'target_type',
            'contents'  => 'GROUP',
        ],
        [
            'name'      => 'filename',
            'contents'  => $filename,
        ],
        [
            'name'      => 'file',
            'contents'  => $file,
            'filename'  => $filename,
            'headers'   => ['Content-Type' => 'image/jpeg']
        ],
    ];

    $client = new Client();

    $options = [
        'headers'       => [
            'Accept'        => 'application/json',
            'Authorization' => "Bearer $this->yammerToken",
        ],
        'multipart'     => $multipart,
    ];
  
    $response = $client->request('POST', 'https://filesng.yammer.com/v4/uploadSmallFile', $options);

    return \json_decode((string)$response->getBody(), true)['id'];
}

Of course, you have to replace class variables with your owns. And the content type by your file's one.

2. Send your message

public function postMessage(string $message, string $file): array
{
    $fileId = $this->yammerFileUpload($file, 'my-file.jpg');

    $client = new Client();

    $options = [
        'headers'   => [
            'Accept'        => 'application/json',
            'Authorization' => "Bearer $this->token",
        ],
        'form_params' => [
            'body'               => $message,
            'group_id'           => $this->groupId,
            'attached_objects[]' => "uploaded_file:$fileId",
        ],
    ];

    $response = $client->request('POST', 'https://www.yammer.com/api/v1/messages.json', $options);

    return \json_decode((string)$response->getBody(), true);
}


来源:https://stackoverflow.com/questions/66062985/how-to-upload-files-on-yammer-api-via-the-azure-upload-small-file-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!