繁体   English   中英

尝试将文件上传到 slack 时出现“no_file_data”错误

[英]"no_file_data" error when trying to upload file to slack

当我尝试通过我的 SlackApp(通过 c# 使用 HttpClient)上传任何文件时,我总是得到以下响应:

{"ok":false,"error":"no_file_data"}

我检查了我的ByteArray (我将文件流式传输到一个数组,然后尝试上传)并将我的数据写回 .txt 和 .jpg - 我尝试了这两种类型的数据。 当我写回它们时,它们是原始文件的精确副本,所以我想我的流式传输和写入ByteArray工作正常。 但是我的上传有些问题。

我将向您展示我的代码:客户端和上传方法:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;


namespace SlackApp
{
    public class SlackClient
    {
        private readonly Uri _webhookUrl;
        private readonly HttpClient _httpClient = new HttpClient {};

        public SlackClient(Uri webhookUrl)
        {
            _webhookUrl = webhookUrl;
        }

        public async Task<HttpResponseMessage> UploadFile(byte[] file)
        {
            var requestContent = new MultipartFormDataContent();
            var fileContent = new ByteArrayContent(file);
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            requestContent.Add(fileContent, "slack", "slack.txt");

            var response = await _httpClient.PostAsync(_webhookUrl, requestContent);
            return response;
        }
    }
}

字节数组的创建:

public class PostFile
{
    String path = @"C:\Users\f.held\Desktop\Held-Docs\dagged.jpg";

    public byte[] ReadImageFile()
    {            
        FileInfo fileInfo = new FileInfo(path);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
        BinaryReader br = new BinaryReader(fs);
        byte[] imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }
}

主要的:

using System;
using System.Net.Http;
using System.Threading.Tasks;


namespace SlackApp
{
    class TestArea
    {
        public static void Main(string[] args)
        {    
            Task.WaitAll(IntegrateWithSlackAsync());
        }

        private static async Task IntegrateWithSlackAsync()
        {
            var webhookUrl = new Uri("https://slack.com/api/files.upload?token=xoxp-hereStandsMyToken&channel=MyChannel");  
            var slackClient = new SlackClient(webhookUrl);
            PostMessage PM = new PostMessage();
            PostFile PF = new PostFile();
            var testFile = PF.ReadImageFile();

            while (true)
            {
                var message = Console.ReadLine(); 
                FormUrlEncodedContent payload = PM.Content(message, "");
                var response = await slackClient.SendMessageAsync(payload);

                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content); //I build these two lines in here so I got the response from the method, and this is where it says "no_file_data"

                var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
                Console.WriteLine($"Received {isValid} response.");
                Console.WriteLine(response); //this puts out a "valid" response - oddly enough
            }
        }
    }
    }

有人知道这里有什么问题吗? 为什么不取数据?

您的代码中有两个错误:

  • main():指定通道的参数叫做channels ,不是channel
  • UploadFile():当您将文件内容添加到多部分时,您需要为文件包含正确的 API 参数file ,而不是slack 并且还想包含一个合理的文件名(而不是slack.txt )。

补充评论

  • UploadFile():将内容类型设置为multipart/form-data 该内容的正确类型是image/jpeg 但是,正确类型的接缝会被自动检测到,因此只需删除该线即可。
  • main():Slack API 将始终返回 OK(http 200,除非存在网络问题),因此您还需要查看 JSON 响应的okerror属性。

这是您的代码的更新版本。 我更改了您的 main() 方法以包含对 `UploadFile()? 的调用。

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;


namespace SlackApp
{
    public class PostFile
    {
        string path = @"C:\Users\Stratios_down.jpg";

        public byte[] ReadImageFile()
        {
            FileInfo fileInfo = new FileInfo(path);
            long imageFileLength = fileInfo.Length;
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            BinaryReader br = new BinaryReader(fs);
            byte[] imageData = br.ReadBytes((int)imageFileLength);
            return imageData;
        }
    }

    public class SlackClient
    {
        private readonly Uri _webhookUrl;
        private readonly HttpClient _httpClient = new HttpClient { };

        public SlackClient(Uri webhookUrl)
        {
            _webhookUrl = webhookUrl;
        }

        public async Task<HttpResponseMessage> UploadFile(byte[] file)
        {
            var requestContent = new MultipartFormDataContent();
            var fileContent = new ByteArrayContent(file);            
            requestContent.Add(fileContent, "file", "stratios.jpg");

            var response = await _httpClient.PostAsync(_webhookUrl, requestContent);
            return response;
        }
    }

    class TestArea
    {
        public static void Main(string[] args)
        {
            Task.WaitAll(IntegrateWithSlackAsync());
        }

        private static async Task IntegrateWithSlackAsync()
        {
            var webhookUrl = new Uri(
                "https://slack.com/api/files.upload?token=xoxp-MY-TOKEN&channels=test"
            );
            var slackClient = new SlackClient(webhookUrl);

            PostFile PF = new PostFile();
            var testFile = PF.ReadImageFile();

            var response = await slackClient.UploadFile(testFile);

            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
            Console.ReadKey();

        }
    }
}

此外,我还有一些建议可以改进您的代码。

  • 我不会在 URL 中包含额外的 API 参数,而是按照 API 文档的建议将它们发送到 POST 请求中。
  • 将文件包含为 FileStream 而不是自己将其加载到 ByteArray 是更好的方法,建议用于较大的文件。
  • 不知道为什么你的 main.js 中需要一个无限循环。 这些真的很糟糕,应该避免。

另请查看我将文件上传到 Slack 的新异步示例,我在其中应用了这两个想法。

我也no_file_datano_file_data错误。 我发现你的文件需要存在并且它需要里面的实际内容。 除了文件存在检查之外,请确保在上传之前进行大小检查或内容长度检查

暂无
暂无

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

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