我正在尝试使用 node.js 和 request package 通过 Slack 上传图像,但运气不太好。我从 API 收到 invalid_array_arg
或 no_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);
});
我看了一些相关的帖子:
- Can I upload an image as attachment with Slack API?
- Slack API (files.upload) using NodeJS
- fix files.upload from Buffer with formData options #307
唯一有效的是直接使用curl命令,但使用cygwin(CommandPrompt失败:curl:(1)协议(protocol)https在libcurl中不支持或禁用
)。从 Node 调用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 上使用 Node 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
。因此,您需要在请求对象中使用 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);
});
关于javascript - 如何在Windows上使用node.js将图像上传到Slack?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651747/