no_file_data error when using Slack API upload

2019-08-13 23:54发布

问题:

I'm getting this error {"ok":false,"error":"no_file_data"} when I try to call the slack API to upload. I already have the specified file in ./log.

robot.respond /upload (.*)/i, (res) ->
    app_name = res.match[1]
    request = require("request")
    fs = require("fs")
    channel_name = res.message.room

    data = {
        channels: channel_name,
        filename: "#{app_name}.txt",
        file: fs.createReadStream("./log/#{app_name}.txt"),
    }

    robot.http("https://slack.com/api/files.upload")
      .headers(Authorization: 'Bearer slack-token', 'Content-Type': 'application/json')
      .post(data) (err, httpRes, body) ->
        if err
          res.send "#{err}"
          return

        res.send "#{body}"

回答1:

This does not work, because the API method files.upload does not support the content type application/json posts.

For your case you need to post as multipart/form-data, with one part containing the file data and one part containing the API parameters including the token.