Search code examples
c#apihttphttpwebrequestrocket.chat

How to upload files from a .NET-Application to a Rocket.Chat-Channel?


I need to make a feedback-form in my .NET application, which sends messages to a Rocket.Chat-Channel (What is Rocket.Chat?).

I am already able to send a textmessage with the api of Rocket.Chat.

I found a documentation, how to send files with an api, but i never had done this before. How can I send the files with my Json?

Someone did that before? Maybe somebody can give me a small example to get this done.

This is the code of my method, which sends the textmessage.

private void SendToRocketChat()
        {
            var baseAddress = "https://plc.ifm-sw.net/api/v1/chat.sendMessage";

            var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
            http.Method = "POST";
            http.ContentType = "application/json";
            http.Headers.Add("X-Auth-Token", "4ZLqSyN9IEFIkj6SqIde2a4orHhEdL8S0eGPEFdfS9C");
            http.Headers.Add("X-User-Id", "rocket.cat");

            string rid = "F24Ydk2kkTXAPWsQ9";

            JObject Json = new JObject(new JProperty("message", new JObject(new JProperty("rid", rid), new JProperty("msg", WebUtility.HtmlEncode(FeedbackText)))));

            ASCIIEncoding encoding = new ASCIIEncoding();
            Byte[] bytes = encoding.GetBytes(Json.ToString());

            Stream newStream = http.GetRequestStream();
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();

            var response = http.GetResponse();

            var stream = response.GetResponseStream();
            var sr = new StreamReader(stream);
            var content = sr.ReadToEnd();
            logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
        }

And this is what i already tried for the Fileupload. Where is my error?

private void SendFileToRocketChat()
        {
            var url = "https://example-sw.net/api/v1/rooms.upload/:gdfgfgdkTXAPWsQ9";
            var filePath = "Abbildung13.jpg";

            var httpClient = (HttpWebRequest)WebRequest.Create(new Uri(url));
            httpClient.Method = "POST";
            httpClient.Headers.Add("X-Auth-Token", "4ZLqSyN9IEhEdLgfd8S0eGPEFdfS9C");
            httpClient.Headers.Add("X-User-Id", "rocket.cat");
            httpClient.ContentType = "multipart/form-data";

            MultipartFormDataContent form = new MultipartFormDataContent();

            FileStream fs = File.OpenRead(filePath);
            var streamContent = new StreamContent(fs);

            var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

            form.Add(imageContent, "file", Path.GetFileName(filePath));
            form.Add(imageContent, "msg", "This is a message with a file");
            form.Add(imageContent, "description", "Simple text file");

            var response = httpClient.GetResponse();

            var stream = response.GetResponseStream();
            var sr = new StreamReader(stream);
            var content = sr.ReadToEnd();
            logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
        }

Solution

  • After some time i got a code, which is working fine. Maybe it will help someone later.

    private void SendFileToRocketChat()
            {
                var url = "https://exampleurl.net/api/v1/rooms.upload/fsgfadgTXAPWsQ9";
                var filePath = "text.zip";
                NameValueCollection formFields = null;
                string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
    
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                request.KeepAlive = true;
                request.Headers.Add("X-Auth-Token", "4ZLqSyN9IEgfasgfdagsdg8S0eGPEFdfS9C");
                request.Headers.Add("X-User-Id", "rocket.bot");
    
                Stream memStream = new System.IO.MemoryStream();
                var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
                string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
    
                string files = filePath;
                if (formFields != null)
                {
                    foreach (string key in formFields.Keys)
                    {
                        string formitem = string.Format(formdataTemplate, key, formFields[key]);
                        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                        memStream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }
    
                string headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\n" + "Content-Type: application/zip\r\n\r\n";
                memStream.Write(boundarybytes, 0, boundarybytes.Length);
                var header = string.Format(headerTemplate, "file", files);
                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                using (var fileStream = new FileStream(files, FileMode.Open, FileAccess.Read))
                {
                    var buffer = new byte[1024];
                    var bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }
    
                memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                request.ContentLength = memStream.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    memStream.Position = 0;
                    byte[] tempBuffer = new byte[memStream.Length];
                    memStream.Read(tempBuffer, 0, tempBuffer.Length);
                    memStream.Close();
                    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                }
                using (var response = request.GetResponse())
                {
                    Stream stream2 = response.GetResponseStream();
                    StreamReader reader2 = new StreamReader(stream2);
                    string res = reader2.ReadToEnd();
    
                    logger.LogInformation(JsonConvert.DeserializeObject(res).ToString().Trim('{', '}'));
                }
            }