如何在 Windows 上使用 node.js 将图像上传到 Slack?

How to upload an image to Slack using node.js on Windows?

我正在尝试使用 node.js 和 request package 通过 Slack 上传图片,但运气不佳。我从 API.

收到 invalid_array_argno_file_data 错误

这是我的要求:

    var options = { method: 'POST',
      url: 'https://slack.com/api/files.upload',
      headers: 
       { 'cache-control': 'no-cache',
         'content-type': 'application/x-www-form-urlencoded' },
      form: 
       { token: SLACK_TOKEN,
         channels: SLACK_CHANNEL,
         file: fs.createReadStream(filepath)
        } };

    request(options, function (error, response, body) {
      if (error) throw new Error(error);

      console.log(body);
    });

我看了一些相关的帖子:

唯一可行的方法是直接使用 curl 命令,但使用 cygwin(命令提示符失败:curl: (1) Protocol https not supported or disabled in libcurl)。从节点调用 curl 的问题(使用 child_process)但在命令提示符中无声地失败并且仍然使用 cygwin returns no_file_data(传递文件的绝对路径):

stdout: {"ok":false,"error":"no_file_data"}
stderr:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   469  100    35  100   434    359   4461 --:--:-- --:--:-- --:--:--  6112

我在 Windows.

上使用节点 v6.9.1

我错过了什么?如何通过 Windows 上的 node.js 将图片上传到 slack?

Slack API错误invalid_array_arg表示传递给Slack的参数格式有问题。 (参见 here

当对 files.upload 使用 file 属性 时,Slack 将数据排除为 multipart/form-data,而不是 application/x-www-form-urlencoded。因此,您需要在请求 object 中使用 formData 而不是 form。我还删除了 header.

中不正确的部分

这个有效:

      var fs = require('fs');
      var request = require('request');

      var SLACK_TOKEN = "xoxp-xxx";
      var SLACK_CHANNEL = "general";
      var filepath = "file.txt";

      var options = { method: 'POST',
      url: 'https://slack.com/api/files.upload',
      headers: 
       { 'cache-control': 'no-cache' },
      formData: 
       { token: SLACK_TOKEN,
         channels: SLACK_CHANNEL,
         file: fs.createReadStream(filepath)
        } };

    request(options, function (error, response, body) {
      if (error) throw new Error(error);

      console.log(body);
    });

在这个示例脚本中,它假设上传一个二进制文件(zip 文件)。当您使用它时,请根据您的环境进行修改。将文件上传到 Slack 时,使用 multipart/form-data。在我的环境中,存在某些库无法上传文件的情况。所以我创造了这个。如果这对您的环境有用,我很高兴。

用户可以通过如下方式转换字节数组上传二进制文件。

  • 首先,它构建表单数据。
  • 添加使用 Buffer.concat() 转换为字节数组和边界的 zip 文件。
  • 这在请求中用作正文。

示例脚本如下

示例脚本:

var fs = require('fs');
var request = require('request');
var upfile = 'sample.zip';
fs.readFile(upfile, function(err, content){
    if(err){
        console.error(err);
    }
    var metadata = {
        token: "### access token ###",
        channels: "sample",
        filename: "samplefilename",
        title: "sampletitle",
    };
    var url = "https://slack.com/api/files.upload";
    var boundary = "xxxxxxxxxx";
    var data = "";
    for(var i in metadata) {
        if ({}.hasOwnProperty.call(metadata, i)) {
            data += "--" + boundary + "\r\n";
            data += "Content-Disposition: form-data; name=\"" + i + "\"; \r\n\r\n" + metadata[i] + "\r\n";
        }
    };
    data += "--" + boundary + "\r\n";
    data += "Content-Disposition: form-data; name=\"file\"; filename=\"" + upfile + "\"\r\n";
    data += "Content-Type:application/octet-stream\r\n\r\n";
    var payload = Buffer.concat([
            Buffer.from(data, "utf8"),
            new Buffer(content, 'binary'),
            Buffer.from("\r\n--" + boundary + "\r\n", "utf8"),
    ]);
    var options = {
        method: 'post',
        url: url,
        headers: {"Content-Type": "multipart/form-data; boundary=" + boundary},
        body: payload,
    };
    request(options, function(error, response, body) {
        console.log(body);
    });
});