博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 模拟POST提交文件
阅读量:6316 次
发布时间:2019-06-22

本文共 2911 字,大约阅读时间需要 9 分钟。

http://blog.csdn.net/hellowjwang/article/details/19975635 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; } } }

 

你可能感兴趣的文章
NFS服务配置
查看>>
中级篇第九期:相册与拍照初使用
查看>>
我的友情链接
查看>>
lvs 一个网卡单个管理ip,多个跨网段VIP解决办法
查看>>
自定义圆角button
查看>>
超长正整数相加
查看>>
Centos 6 编译内核支持LVS-SNAT模式
查看>>
JAVA数据类型
查看>>
TCP segment of a reassembled PDU
查看>>
hdu 5195 DZY Loves Topological Sorting BestCoder Round #35 1002 [ 拓扑排序 + 优先队列 || 线段树 ]...
查看>>
针对单个 js 文件禁用 ESLint 语法校验
查看>>
【Oracle】oracle中快速判断某一日期是闰年或平年
查看>>
datatable 转 json 格式
查看>>
vs2010生成Dll文件并引用dll(C#)
查看>>
藏在兰州拉面里精益管理秘诀
查看>>
How to blog on Github
查看>>
百思不得姐 one day
查看>>
19.04.16--指针笔记-参数传递
查看>>
面向对象
查看>>
POJ1860 Currency Exchange
查看>>