繁体   English   中英

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

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

我正在尝试使用node.js和request包通过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(CommandPrompt失败: curl: (1) Protocol https not supported or disabled in libcurl )。 从节点调用curl的问题(使用child_process ),但在命令提示符中无提示地失败,并且仍然使用cygwin返回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的参数格式存在问题。 (请参阅此处

file属性用于files.upload ,Slack files.upload数据作为multipart/form-data而不是application/x-www-form-urlencoded 因此,您需要在请求对象中使用formData而不是form 我还删除了标题中的不正确部分。

这有效:

      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);
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM