How to create a Slack message containing an uploaded image?

How to create a Slack message containing an uploaded image?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Combining Text and Images in Slack API Messages

When building a bot or integrating with Slack via PHP, it is common to hit a wall where standard documentation shows how to send a text block and how to upload an image separately, but leaves you guessing on how to merge them into a single payload. The core issue usually stems from misunderstanding how the files parameter interacts with the message body in the Chat API.

You can indeed send a text-only message and an image-only message sequentially, but that results in two distinct events in the channel history. To achieve the goal of sending both in one atomic operation, you must utilize the chat.postMessage endpoint with specific file attachment parameters.

The Slack API allows you to attach a file directly to a message without needing to upload it first as a separate step, provided you handle the encoding correctly. The critical parameter here is file, not files. While pluralizing might seem logical for batch operations, the API expects a single string containing a Base64-encoded image when sending inline attachments, or a JSON object containing a file ID if the file has already been uploaded to Slack's storage.

Handling Local Images with Base64

Since your use case involves creating an image "on-the-fly" locally within a PHP script, you are working with binary data that needs to traverse the HTTP request body. The most straightforward approach for inline images is to convert the local image file into a Base64 string before sending it to the API.

In PHP, you can read the file contents and encode them using base64_encode. However, you must be mindful of the content type. If you are sending a PNG or JPEG, the API expects the header of the encoded string to indicate the MIME type if you were parsing it elsewhere, but for the chat.postMessage endpoint with an inline attachment, the payload structure changes slightly depending on how you pass the data.

The most robust method that avoids pre-uploading is passing the Base64 content in a specific format. The Slack API accepts a JSON object where the file key holds a string representation of the file. For inline images, this often looks like this:

{
  "text": "Here is a dynamic image generated by our system.",
  "file": {
    "filename": "generated_chart.png",
    "title": "Live Metrics",
    "image_data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
    "mime_type": "image/png"
  }
}

However, the exact structure depends on whether you are using a bot token or an app token with specific scopes. If you are sending via chat.postMessage, passing a raw Base64 string directly to the file parameter often fails unless the API is configured to accept inline base64, which it generally does not for security reasons in older versions. The modern and reliable approach is to use the files.upload endpoint first to get a file ID, then reference that ID in your message.

The Two-Step Upload Pattern

If direct Base64 injection proves unreliable due to scope restrictions or API versioning, the two-step pattern you initially tried is actually the intended architecture for production-grade bots. First, call files.upload with the local image data and the filename. This returns a JSON response containing a unique file ID. Second, use chat.postMessage with the attachments parameter to include that file ID.

$token = 'xoxb-your-bot-token';
$channelId = 'C0123456789';

// Step 1: Upload the image to get a File ID
$response = curl_exec("https://slack.com/api/files.upload");
$body = json_decode($response, true);

if ($body['ok']) {
    $fileId = $body['file']['id'];

    // Step 2: Send the message with the text and the uploaded file ID
    $messagePayload = [
        'channel' => $channelId,
        'text' => 'Check out this generated image.',
        'attachments' => [
            [
                'type' => 'image',
                'url' => "https://files.slack.com/files/pri/{$fileId}/", // Constructing the URL requires care with file types
                'title' => 'Generated Report'
            ]
        ],
        'filename' => 'generated_report.png' // Ensure filename matches upload if strict checking is on
    ];

    curl_setopt_array($ch, [
        CURLOPT_URL => "https://slack.com/api/chat.postMessage",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($messagePayload)
    ]);

    $result = curl_exec($ch);
} else {
    // Handle upload failure
    log_error("Failed to upload file: " . print_r(json_decode($response), true));
}

Trade-offs and Common Pitfalls

The primary trade-off between the two methods is atomicity versus reliability. Direct Base64 injection feels atomic because it happens in one HTTP request, but it is brittle; if the image size exceeds limits or the MIME type is inferred incorrectly, the message fails silently or throws a generic error. The upload-first approach guarantees that the file exists in Slack's CDN before the message is sent, ensuring consistent rendering across different client applications (desktop app vs. mobile).

Another common mistake is failing to set the correct filename and mimetype during the upload step. If these are missing or incorrect, Slack may default to a generic icon or strip the image entirely when rendering the attachment. Always explicitly pass filename and content_type (or mimetype) in your files.upload payload to ensure the image renders with the correct extension and color depth.

For developers looking for deeper integration patterns regarding file handling, you might find additional insights at https://laravelcompany.com, specifically if you are building a Laravel-based bot where queueing these upload tasks can prevent blocking your main application thread.

Our network