Send multipart/form-data content type request

孤街浪徒 提交于 2019-11-30 05:42:40
Darin Dimitrov

---27311326571405 is called boundary and it is a random string that should never appear in the data you are sending and is used as separator between the values.

Here's an example of sending such a request to a given address:

class Program
{
    static void Main()
    {
        var data = new List<KeyValuePair<string, string>>(new[]
        {
            new KeyValuePair<string, string>("list", "8274184"),
            new KeyValuePair<string, string>("list", "8274174"),
            new KeyValuePair<string, string>("list", "8274178"),
            new KeyValuePair<string, string>("antirobot", "2341234"),
            new KeyValuePair<string, string>("votehidden", "1"),
        });

        string boundary = "----MyAppBoundary" + DateTime.Now.Ticks.ToString("x");

        var request = (HttpWebRequest)WebRequest.Create("http://example.com");
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";

        using (var requestStream = request.GetRequestStream())
        using (var writer = new StreamWriter(requestStream))
        {
            foreach (var item in data)
            {
                writer.WriteLine("--" + boundary);
                writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                writer.WriteLine();
                writer.WriteLine(item.Value);
            }
            writer.WriteLine(boundary + "--");
        }

        using (var response = request.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}
mvds

It is a semi-random string, used to distinguish the different fields. In the content-type header this is given as the boundary.

see what-are-valid-characters-for-creating-a-multipart-form-boundary

Ankit kumar

If you like to remove ---27311326571405 boundary value in response, please use the following code

var multiplarty = require('multiparty')
var util = require('util')
if ( req.method === 'POST') {
  var form = new multiplarty.Form();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields}));
  });

  return;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!