日期:2014-05-17 浏览次数:20692 次
在基于Http协议的Post请求中,Content-type为application/x-www-form-urlencoded的传输只能传送非文件的数据。
如果想用Http的Post方法来上传数据及文件,需要实现Content-type为multipart/form-data类型的协议程序。
下面是参考了StackOverflow网站上的一个例子,实现了关于客户端上传文件的功能类,代码如下:
using System; using System.Net; using System.Text; using System.Collections.Generic; using System.IO; namespace ZDWorks.ZDClock.Cloud { /// <summary> /// 文件类型数据的内容参数 /// </summary> public class FileParameter { // 文件内容 public byte[] File { get; set; } // 文件名 public string FileName { get; set; } // 文件内容类型 public string ContentType { get; set; } public FileParameter(byte[] file) : this(file, null) { } public FileParameter(byte[] file, string filename) : this(file, filename, null) { } public FileParameter(byte[] file, string filename, string contentType) { File = file; FileName = filename; ContentType = contentType; } } /// <summary> /// 数据与文件http请求 /// </summary> public class HttpMultipartFormRequest { #region Data Members private readonly Encoding DefaultEncoding = Encoding.UTF8; private ResponseCallback m_Callback; private byte[] m_FormData; #endregion #region Constructor public HttpMultipartFormRequest() { } #endregion #region Delegate public delegate void ResponseCallback(string msg); #endregion public void AsyncHttpRequest(string postUri, Dictionary<string, object> postParameters, ResponseCallback callback) { // 随机序列,用作防止服务器无法识别数据的起始位置 string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); // 设置contentType string contentType = "multipart/form-data; boundary=" + formDataBoundary; // 将数据转换为byte[]格式 m_FormData = GetMultipartFormData(postParameters, formDataBoundary); // 回调函数 m_Callback = callback; // 创建http对象 HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(postUri)); // 设为post请求 request.Method = "POST"; request.ContentType = contentType; // 请求写入数据流 request.BeginGetRequestStream(GetRequestStreamCallback, request); } private void GetRequestStreamCallback(IAsyncResult ar) { HttpWebRequest request = ar.AsyncState as HttpWebRequest; using (var postStream = request.EndGetRequestStream(ar)) { postStream.Write(m_FormData, 0, m_FormData.Length); postStream.Close(); } request.BeginGetResponse(GetResponseCallback, request); } private void GetResponseCallback(IAsyncResult ar) { // 处理Post请求返回的消息 try { HttpWebRequest request = ar.AsyncState as HttpWebRequest; HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse; using (var stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream); string msg = reader.ReadToEnd(); if (m_