从HttpListenerRequest获取表单数据 [英] Getting form data from HttpListenerRequest

查看:1444
本文介绍了从HttpListenerRequest获取表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HttpListenerRequest这是从开始的HTML <形式为GT; 被张贴。我需要知道如何让发布表单值+上传的文件。有谁知道一个例子给我节省时间做我自己?我已经围绕谷歌,但没有发现使用的东西。

I have a HttpListenerRequest which was initiated from a html <form> that was posted. I need to know how to get the posted form values + the uploaded files. Does anyone know of an example to save me the time doing it for myself? I've had a google around but not found anything of use.

推荐答案

要了解的主要事情是的HttpListener是低级工具与ht​​tp请求的工作。各邮政局数据在HttpListenerRequest.InputStream流。假设我们有一个这样的形式:

The main thing to understand is that HttpListener is a low level tool to work with http requests. All post data is in HttpListenerRequest.InputStream stream. Suppose we have a form like that:

<form method=\"post\" enctype=\"multipart/form-data\"><input id=\"fileUp\" name=\"fileUpload\" type=\"file\" /><input type=\"submit\" /></form>

现在我们希望看到帖子的数据。让我们实现这样做的方法:

Now we want to see the post data. Lets implement a method to do this:

public static string GetRequestPostData(HttpListenerRequest request)
{
  if (!request.HasEntityBody)
  {
    return null;
  }
  using (System.IO.Stream body = request.InputStream) // here we have data
  {
    using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
    {
      return reader.ReadToEnd();
    }
  }
}



上传一些文件,看看结果

upload some file and see result:

Content-Disposition: form-data; name="somename"; filename="D:\Test.bmp" 
Content-Type: image/bmp
...here is the raw file data...

接下来假设我们有简单的形式,而不上传文件:

Next suppose we have simple form without uploading files:

<form method=\"post\">First name: <input type=\"text\" name=\"firstname\" /><br />Last name: <input type=\"text\" name=\"lastname\" /><input type=\"submit\" value=\"Submit\" /></form>

让我们来看看输出:

firstname=MyName&lastname=MyLastName

组合形式的结果:

Content-Disposition: form-data; name="firstname"
My Name
Content-Disposition: form-data; name="somename"; filename="D:\test.xls"
Content-Type: application/octet-stream
...raw file data...

正如你可以简单的形式的情况下,看你刚才读的InputStream串并分析后的值。如果有一个更复杂的形式 - 你需要执行更复杂的分析,但它仍然是可以做到的。希望这个例子将节省您的时间。注意,并不总是读取所有数据流作为字符串的情况。

As you can see in case of simple form you can just read InputStream to string and parse post values. If there is a more complex form - you need to perform more complex parsing but it's still can be done. Hope this examples will save your time. Note, that is not always the case to read all stream as a string.

这篇关于从HttpListenerRequest获取表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆