使用jquery

时间:2017-08-02 21:49:24

标签: javascript jquery ajax slack slack-api

我试图在网页上选择一个文件并通过Slack API在Slack中发布。

我原本在做:

var request = require('request');
$(".submit").click(function(){
    request.post({
    url: 'https://slack.com/api/files.upload',
    formData: {
        token: "myTokenHere",
        title: "Image",
        filename: "image.png",
        filetype: "auto",
        channels: "mychannel",
        file: document.getElementById('idofuploadelement').files[0]
    },
}, function (err, response) {
    console.log(JSON.parse(response.body));
});

然后我转而尝试使用Ajax,以便我不必包含require。

$(".submit").click(function(){
$.ajax({
    type: "POST",
    method: "POST",
    enctype: "multipart/form-data",
    url: 'https://slack.com/api/files.upload',
    formData: {
        token: "myTokenHere",
        title: "Image",
        filename: "image.png",
        filetype: "auto",
        channels: "mychannel",
        file: document.getElementById('idofuploadelement').files[0]
        }   
}).done(function(url) {
    console.log(url);
            });
});

但这给了我控制台警告 Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent. 即使我有这些属性(我在添加它们之前也得到了错误),我仍然会收到错误。

我的html是简单的html5输入标签(用于上传和提交按钮)

<input type="file" name="fileToUpload" id="idofuploadelement">
<input type="submit" name="submit" class="submit action-button next" value="Next"/>

简而言之,我试图将文件发送给我(无论如何,Slack,Github,电子邮件,无论如何),而无需启动服务器。有可能吗?

1 个答案:

答案 0 :(得分:1)

想出来:

HTML:

<form id="myform" method="POST" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="file-select">
    <input id="upload-button" type="submit" name="submit" class="submit action-button next" value="Next"/>
</form>

JS:

var form = document.getElementById('myform');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
    event.preventDefault();
    // Update button text.
    uploadButton.innerHTML = 'Uploading...';
    var file = fileSelect.files[0];
    var formData = new FormData();
    formData.append('file', file, file.name);
    formData.append('token', insert_token_here);
    formData.append('channels', insert_channel_here);
    var xhr = new XMLHttpRequest();
    xhr.open('POST','https://slack.com/api/files.upload', true);

    // Set up a handler for when the request finishes.
    xhr.onload = function () {
      if (xhr.status === 200) {
        // File(s) uploaded.
        uploadButton.innerHTML = 'Uploaded';
      } else {
        alert('An error occurred!');
      }
    };
    xhr.send(formData);
}