Windows Phone7 实现文件上传
在基于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_Callback != null) { m_Callback(msg); } } } catch (Exception e) { string a = e.ToString(); if (m_Callback != null) { m_Callback(string.Empty); } } } private byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { Stream formDataStream = new MemoryStream(); bool needsCLRF = false; foreach (var param in postParameters) { if (needsCLRF) { formDataStream.Write(DefaultEncoding.GetBytes("\r\n"), 0, DefaultEncoding.GetByteCount("\r\n")); } needsCLRF = true; if (param.Value is FileParameter) { FileParameter fileToUpload = (FileParameter)param.Value; string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, param.Key, fileToUpload.FileName ?? param.Key, fileToUpload.ContentType ?? "application/octet-stream"); // 将与文件相关的header数据写到stream中 formDataStream.Write(DefaultEncoding.GetBytes(header), 0, DefaultEncoding.GetByteCount(header)); // 将文件数据直接写到stream中 formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, param.Value); formDataStream.Write(DefaultEncoding.GetBytes(postData), 0, DefaultEncoding.GetByteCount(postData)); } } string tailEnd = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(DefaultEncoding.GetBytes(tailEnd), 0, DefaultEncoding.GetByteCount(tailEnd)); // 将Stream数据转换为byte[]格式 formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; } } }
转自:http://blog.csdn.net/moxiaomomo/article/details/7902064