c#如何post文件流

2020-06-16 科技 114阅读

C#中post用法如下:

首先,POST请求会把请求的数据放置在HTTP请求包的包体中。

其次,POST,由于不是URL传值,理论上是不会受限制的,但是实际上各个服务器会规定对POST提交数据大小进行限制,Apache、IIS都有各自的配置。

最后,POST的安全性较高。

通过C#post文件流的如下代码为:

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.IO;using System.Net;

using System.Text;

public class HttpPost{

///

    ///

以Post 形式提交数据到 uri

///     ///

///

///

///

public static byte[] Post(Uri uri, IEnumerable files, NameValueCollection values)    {

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

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.ContentType = "multipart/form-data; boundary=" + boundary;

request.Method = "POST";

request.KeepAlive = true;

request.Credentials = CredentialCache.DefaultCredentials;

MemoryStream stream = new MemoryStream();

byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//提交文本字段

if (values != null)

{

string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

foreach (string key in values.Keys)

{

string s = string.Format(format, key, values[key]);

byte[] data = Encoding.UTF8.GetBytes(s);

stream.Write(data, 0, data.Length);

}

stream.Write(line, 0, line.Length);        }

//提交文件

if (files != null)

{

string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

foreach (UploadFile file in files)

{                string s = string.Format(fformat, file.Name, file.Filename);

byte[] data = Encoding.UTF8.GetBytes(s);

stream.Write(data, 0, data.Length);

stream.Write(file.Data, 0, file.Data.Length);

stream.Write(line, 0, line.Length);

}        }

request.ContentLength = stream.Length;

Stream requestStream = request.GetRequestStream();

stream.Position = 0L;

stream.CopyTo(requestStream);

stream.Close();

requestStream.Close();

using (var response = request.GetResponse())

using (var responseStream = response.GetResponseStream())

using (var mstream = new MemoryStream())

{            responseStream.CopyTo(mstream);

return mstream.ToArray();        }    }

///

    /// 上传文件

///

public class UploadFile

{

public UploadFile()

{

ContentType = "application/octet-stream";        }

public string Name { get; set; }

public string Filename { get; set; }

public string ContentType { get; set; }

public byte[] Data { get; set; }    }}

声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com