【发布时间】:2019-11-18 15:10:44
【问题描述】:
我想通过 Telegram 中的机器人向用户发送本地图像文件,但似乎不知道该怎么做。
Telegram 网站指出,要做到这一点,我应该使用 multipart/form-data 并以“通常的方式”发送图像。在查找 multipart/form-data 后,我目前正在尝试将文件上传到表单并将表单数据发送到 Telegram API。
let form = document.createElement("FORM");
form.setAttribute("action", "https://api.telegram.org/bot{some token}/sendMessage");
form.setAttribute("method", "POST");
form.setAttribute("id", "f");
form.setAttribute("enctype", "multipart/form-data");
let file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("value", "\some\local\path");
file.setAttribute("id", "file");
let text = document.createElement("input");
text.setAttribute("type", "text");
text.setAttribute("name", "text");
text.setAttribute("value", '"test"');
let ID = document.createElement("input");
ID.setAttribute("type", "text");
ID.setAttribute("name", "chat_ID")
ID.setAttribute("value", "123456789");
let s = document.createElement("input");
s.setAttribute("type", "submit");
form.appendChild(text);
form.appendChild(ID);
form.appendChild(s);
form.appendChild(file);
document.getElementsByTagName("body")[0].appendChild(form);
var formJSON = $("form").serializeArray();
console.log(formJSON);
var j = "{"
for (let i = 0; i < formJSON.length; i++) {
j += '"' + (formJSON[i]["name"]) + '"' + ":" + (formJSON[i]["value"]);
if (i != formJSON.length - 1) {
j += ",";
}
}
j += "}";
jP = JSON.parse(String(j));
console.log(document.getElementById("file").files);
form.setAttribute("action", "https://api.telegram.org/bot{some token}/sendPhoto?" + "chat_id=" + (jP["chat_ID"]) + "&photo=" + "\some\local\path");
document.getElementById("f").submit();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js" />
<head>
<meta charset="utf-8" />
<title>This is a test</title>
</head>
<body>
</body>
<script src="formData.js" />
</html>
目前我不确定文件是否正在上传,因为当我在 Chrome 上运行 HTML 时,没有选择文件并且 fileList 为空。此外,Telegram 坚持将数据作为 JSON 发送(这就是我将表单数据解析为 JSON 的原因)。我尝试传递本地文件路径,但似乎认为我正在尝试在 Telegram 服务器上查找文件 ID。我不确定如何从这里开始。
【问题讨论】:
标签: javascript html forms telegram