• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c#模拟提交有附件表单(转)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

最近项目需要,需要在winform中模拟表单将数据提交至服务器,发现单独提交键值对很容易实现,单独实现上传文件也很容易实现。要是同时提交键值对和文件,比较麻烦。在百度谷歌了大半天没有任何收获。无奈之下,按照 黑月.Net的 的思路去自己写。经过奋斗 终于搞定。
方法如下:


public WebResponse SubmitData(string fileName, Uri uri, string[] keys, string[] values)
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest2.Credentials = credentialCache;//
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";

// Build up the post message header

StringBuilder sb = new StringBuilder();

if (keys != null)
{
for (int i = 0; i < keys.Length; i++)
{
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + keys[i] + "\"\r\n\r\n");
sb.Append(values[i]);
sb.Append("\r\n");
}
}


sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"");
sb.Append(Path.GetFileName(fileName));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");

string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
httpWebRequest2.ContentLength = length;

Stream requestStream = httpWebRequest2.GetRequestStream();

// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);

// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

WebResponse webResponse2 = httpWebRequest2.GetResponse();
return webResponse2;

}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中[WebMethod]的用法,aspx、ashx、asmx发布时间:2022-07-10
下一篇:
C#中自定义属性的例子发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap