上传文件到WebService
客户端代码
先把文件进行base64位转码
public void UploadFile() { try { System.Net.WebClient webClient = new System.Net.WebClient(); string Url = webServiceUrl + "/WebServiceToAndroid.asmx/UpdateFile"; DirectoryInfo dir = new DirectoryInfo(GetXFilePath()); FileInfo[] files = dir.GetFiles(); if (files != null && files.Any()) { FileInfo fl = files.Where(p => p.Extension.ToLower() != ".log").OrderBy(p => p.CreationTime).FirstOrDefault(); FileStream fs = new FileStream(fl.FullName, FileMode.OpenOrCreate, FileAccess.Read); byte[] bytes = ReadFile(fs); string base64Str = Convert.ToBase64String(bytes).Replace("+", "%2B");//加号不替换掉 转换的时候会出问题 Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("base64Str", base64Str); dic.Add("fileName", fl.Name); HttpWebResponse req = HttpUtils.CreatePostHttpResponse(Url, dic, Encoding.Default); } } catch (Exception ex) { LogUtil.ErrorLog(string.Format("上传XFile文件失败:{0}", ex.Message)); } }
public class HttpUtils { private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset) { HttpWebRequest request = null; //HTTPSQ请求 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = DefaultUserAgent; //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } byte[] data = charset.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } }
服务端接收
[WebMethod(Description = "上传文件")] [ScriptMethod(UseHttpGet = false)] public string UpdateFile(string base64Str, string fileName) { WSResponse result = new WSResponse(); try { byte[] arr = Convert.FromBase64String(base64Str); System.IO.MemoryStream ms = new System.IO.MemoryStream(arr); string filePath = XFileUrl + "/" + fileName; Path.ChangeExtension(filePath, DateTime.Now.ToString("yyyyMMDDHHmmss")); FileStream fs = new FileStream(filePath, FileMode.Create); fs.Close(); fs.Dispose(); using (StreamWriter sw = new StreamWriter(filePath)) { ms.WriteTo(sw.BaseStream); sw.Flush(); } ms.Dispose(); ms.Close(); result.Result = 1; result.Message = "上传成功"; LogUtils.InfoLog("END:" + fileName); } catch (Exception ex) { LogUtils.InfoLog("Base64String转为文件失败!:" + ex.Message + "-" + ex.StackTrace); result.Result = 0; result.Message = "上传失败"; } string resultMsg = Newtonsoft.Json.JavaScriptConvert.SerializeObject(result); return resultMsg; }