Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image to Slack with axios

I'm trying to upload an image to slack using the slack api https://api.slack.com/methods/files.upload.

function uploadImage(file) {
    var form = new FormData();
    form.append('image', file);
    var self = this;
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    var token = 'myToken'
    axios.post('https://slack.com/api/files.upload?token=' + token, form, config)
        .then(function (response) {
            console.log(response);
            self.imageUploaded("Image uploaded")
        })
        .catch(function (error) {
            console.log(error);
            self.error(error);
        })
}

I'm getting response with "invalid form data". Any idea what might be going wrong?

Thanks and best regards!

PS: I was able to post an image to slack with python

def post_image(filename, token, channels):
    f = {'file': (filename, open(filename, 'rb'))}
    response = requests.post(url='https://slack.com/api/files.upload',
                             data={'token': token, 'channels': channels}, 
                             headers={'Accept': 'application/json'}, 
                             files=f)
    return response.tex

Just need to make the same request with axioms

like image 832
MichaelRazum Avatar asked Apr 25 '17 09:04

MichaelRazum


People also ask

How do I upload files using Axios post?

const axios = require('axios'); const FormData = require('form-data'); const fs = require('fs/promises'); // Read image from disk as a Buffer const image = await fs. readFile('./stickers. jpg'); // Create a form and append image with additional fields const form = new FormData(); form.

Can we send files in Slack?

What types of files can I share in Slack? You can share just about any file type up to 1GB in size in Slack from your device, or add them from a file management app like Box, Dropbox, Google Drive, or OneDrive.

How can I get token in Slack?

Visit the App Directory at my.slack.com/apps/manage on your desktop. Click Edit configuration next to the integration. On the configuration page, click Regenerate below the current token. This is the new token that you can use anywhere you need it.


1 Answers

you can upload a file using axios with the form-data lib

const fs = require("fs"); 
const axios = require("axios");
const FormData = require("form-data");


const form = new FormData();

form.append("token", 'token here');
form.append("channels", channelId);
form.append("file", fs.createReadStream(__dirname + "/aapl.png"), 'file name');

try {
  const res = await axios.post("https://slack.com/api/files.upload", form, {
    headers: form.getHeaders(),
  });
} catch (err) {
  throw new Error(err);
}
like image 155
Ericgit Avatar answered Oct 10 '22 02:10

Ericgit