public static string HttpPostData(string url, MsMultiPartFormData form, string filePath, string fileKeyName = "file", int timeOut = 360000) { string result = ""; WebRequest request = WebRequest.Create(url); request.Timeout = timeOut; FileStream file = new FileStream(filePath, FileMode.Open); byte[] bb = new byte[file.Length]; file.Read(bb, 0, (int)file.Length); file.Close(); string fileName = Path.GetFileName(filePath); form.AddStreamFile(fileKeyName, fileName, bb); form.PrepareFormData(); request.ContentType = "multipart/form-data; boundary=" + form.Boundary; request.Method = "POST"; Stream stream = request.GetRequestStream(); foreach (var b in form.GetFormData()) { stream.WriteByte(b); } stream.Close(); WebResponse response = request.GetResponse(); using (var httpStreamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { result = httpStreamReader.ReadToEnd(); } response.Close(); request.Abort(); return(result); }
string UPLOADFILE_SERVICE_URL = "http://.....";//最终接收文件上传的服务接口 public void ProcessRequest(HttpContext context) { object result = null; string temSavePath = context.Server.MapPath(@"~\") + RootFolder; if (!Directory.Exists(temSavePath)) { Directory.CreateDirectory(temSavePath); } if (context.Request.Files != null && context.Request.Files.Count > 0) { HttpPostedFile file = context.Request.Files[0]; string saveFileName = String.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddhhmmssffff"), Path.GetExtension(file.FileName));//保存文件名称 string fileName = String.Format(@"{0}\{1}", temSavePath, saveFileName); file.SaveAs(@"D:\backup\develop\vsSpace\BookIms\BookIms\images\" + fileName); MsMultiPartFormData form = new MsMultiPartFormData(); string decodeName = HttpUtility.UrlDecode(Path.GetFileName(fileName)); //最终服务器会按原文件名保存文件,所以需要将文件名编码下,防止中文乱码 string rst = PostDataServer.HttpPostData(UPLOADFILE_SERVICE_URL, form, fileName, decodeName); context.Response.Write(rst); //输出上传文件返回结果 context.Response.End(); } }