7

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

MichaelRazum
  • 789
  • 1
  • 10
  • 26
  • In the same page Errors section it says "invalid form data" == `The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.` – Vinod Louis Apr 25 '17 at 09:43
  • Any Idea why the form data may be invalid? I also tried form.append('image', file);. The File object looks correct. – MichaelRazum Apr 25 '17 at 09:51
  • send all data in post as {att:value} pair as given in the table use same names like {token:"XXX",filetype:"",filename:"", ... content or file} – Vinod Louis Apr 25 '17 at 09:56
  • I tried this code code var postForm = { token: token, filetype: "auto", filename: "upload.png", file: file } axios.post('https://slack.com/api/files.upload',postForm , config) and also tried to JSON.stringify(postForm) still getting the same response – MichaelRazum Apr 25 '17 at 10:10

1 Answers1

1

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);
}
Ericgit
  • 6,089
  • 2
  • 42
  • 53