作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要在我的 .NET 应用程序中制作一个反馈表单,它将消息发送到 Rocket.Chat-Channel ( What is Rocket.Chat? )。
我已经可以使用 Rocket.Chat 的 api 发送短信了。
我找到了一个 documentation ,如何使用 api 发送文件,但我以前从未这样做过。如何使用我的 Json 发送文件?
有人这样做过吗?也许有人可以给我一个小例子来完成这项工作。
这是我发送文本消息的方法的代码。
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('{', '}'));
}
这是我已经为文件上传尝试过的。我的错误在哪里?
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('{', '}'));
}
最佳答案
一段时间后,我得到了一个代码,它工作正常。也许它会对以后的人有所帮助。
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('{', '}'));
}
}
关于c# - 如何将文件从 .NET 应用程序上传到 Rocket.Chat-Channel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191015/
我是一名优秀的程序员,十分优秀!