import os
import requests
response = requests.post(
"https://slack.com/api/files.upload",
files={"file": open("/path/to/file.txt", "rb")},
data={
"token": os.environ["SLACK_TOKEN"],
"channels": os.environ["SLACK_CHANNELS"]
}
)
response.raise_for_status()
print(response.json())
import os
import httpx
with httpx.Client() as client:
response = client.post(
"https://slack.com/api/files.upload",
files={"file": open("/path/to/file.txt", "rb")},
data={
"token": os.environ["SLACK_TOKEN"],
"channels": os.environ["SLACK_CHANNELS"]
}
)
response.raise_for_status()
print(response.json())
import fetch from 'node-fetch';
import fs from 'fs';
import { env } from 'process';
const response = await fetch('https://slack.com/api/files.upload', {
method: 'POST',
body: new FormData()
.append('token', env.SLACK_TOKEN)
.append('channels', env.SLACK_CHANNELS)
.append('file', fs.createReadStream('/path/to/file.txt'), {
filename: 'file.txt',
contentType: 'text/plain'
}),
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log(data);
import axios from 'axios';
import fs from 'fs';
import { env } from 'process';
const response = await axios.post(
'https://slack.com/api/files.upload',
new FormData()
.append('token', env.SLACK_TOKEN)
.append('channels', env.SLACK_CHANNELS)
.append('file', fs.createReadStream('/path/to/file.txt'), {
filename: 'file.txt',
contentType: 'text/plain'
})
);
console.log(response.data);
package main
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
token := os.Getenv("SLACK_TOKEN")
channels := os.Getenv("SLACK_CHANNELS")
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("token", token)
_ = writer.WriteField("channels", channels)
file, err := os.Open("/path/to/file.txt")
if err != nil {
panic(err)
}
defer file.Close()
part, err := writer.CreateFormFile("file", "file.txt")
if err != nil {
panic(err)
}
_, err = io.Copy(part, file)
if err != nil {
panic(err)
}
_ = writer.Close()
req, err := http.NewRequest("POST", "https://slack.com/api/files.upload", body)
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic("request failed")
}
// Read response body
// ...
}
<?php
$token = getenv('SLACK_TOKEN');
$channels = getenv('SLACK_CHANNELS');
$client = new CURLClient();
$client->setOption(CURLOPT_URL, 'https://slack.com/api/files.upload');
$client->setOption(CURLOPT_POST, true);
$client->setOption(CURLOPT_POSTFIELDS, [
'token' => $token,
'channels' => $channels,
'file' => new CURLFile('/path/to/file.txt', 'text/plain', 'file.txt')
]);
$response = $client->execute();
if ($response === false) {
throw new Exception('Request failed');
}
$httpCode = $client->getInfo(CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
print_r($data);
$client->close();
require 'net/http'
require 'uri'
require 'mime/types'
token = ENV['SLACK_TOKEN']
channels = ENV['SLACK_CHANNELS']
uri = URI.parse('https://slack.com/api/files.upload')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post::Multipart.new(uri.path, {
'token' => token,
'channels' => channels,
'file' => UploadIO.new(File.open('/path/to/file.txt'), 'text/plain', 'file.txt')
})
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error: #{response.code}"
end
puts JSON.parse(response.body)
import Foundation
let token = ProcessInfo.processInfo.environment["SLACK_TOKEN"] ?? ""
let channels = ProcessInfo.processInfo.environment["SLACK_CHANNELS"] ?? ""
let url = URL(string: "https://slack.com/api/files.upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=--\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"token\"\r\n\r\n".data(using: .utf8)!)
body.append(token.data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"channels\"\r\n\r\n".data(using: .utf8)!)
body.append(channels.data(using: .utf8)!)
body.append("\r\n".data(using: .utf8)!)
let fileData = try Data(contentsOf: URL(fileURLWithPath: "/path/to/file.txt"))
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.txt\"\r\n".data(using: .utf8)!)
body.append("Content-Type: text/plain\r\n\r\n".data(using: .utf8)!)
body.append(fileData)
body.append("\r\n".data(using: .utf8)!)
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
fatalError("Request failed: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
fatalError("HTTP error")
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::env;
use std::fs::File;
use std::io::Read;
use reqwest::multipart;
use reqwest::blocking::Client;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = env::var("SLACK_TOKEN")?;
let channels = env::var("SLACK_CHANNELS")?;
let client = Client::new();
let file = File::open("/path/to/file.txt")?;
let form = multipart::Form::new()
.file("file", "/path/to/file.txt")?
.text("token", token)
.text("channels", channels);
let response = client
.post("https://slack.com/api/files.upload")
.multipart(form)
.send()?;
if !response.status().is_success() {
return Err("Request failed".into());
}
let body = response.text()?;
println!("{}", body);
Ok(())
}
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var token = Environment.GetEnvironmentVariable("SLACK_TOKEN");
var channels = Environment.GetEnvironmentVariable("SLACK_CHANNELS");
using var client = new HttpClient();
using var form = new MultipartFormDataContent();
var fileContent = new StreamContent(File.OpenRead("/path/to/file.txt"));
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
form.Add(new StringContent(token), "token");
form.Add(new StringContent(channels), "channels");
form.Add(fileContent, "file", "file.txt");
var response = await client.PostAsync("https://slack.com/api/files.upload", form);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Request failed");
}
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}