c#文件上传 客户端将文件转换成base64 服务端将base64转换成文件并保存在本地

客户端

  //参数
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("imgbases", bb);
                    dic.Add("WJM", DateTime.Now.ToString("yyyyMMddHHmmssfff") + DR["WENJIANMING"] + "".Trim());
                    dic.Add("WJLX", DR["WENJIANLEIXING"] + "".Trim());
                    string message = "";
        message = PostUrl("http://localhost:3878/MainService.asmx/ImagToBase64", dic, ref message);


        //解析返回的数据  XML格式
        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        xmlDoc.Load(ms);
                    System.Xml.XPath.XPathNavigator xpnRoot = xmlDoc.CreateNavigator();
        XmlElement node = xmlDoc.DocumentElement;
        string err = node.InnerText;

        public string PostUrl(string url, Dictionary<string, string> dic, ref string message)
        {
            string result = "";
            try
            {
                System.GC.Collect();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                //req.Timeout = 30000;
                req.AllowAutoRedirect = false;


                //public static string Text = "text/plain";
                //public static string JSON = "application/json";
                //public static string Javascript = "application/javascript";
                //public static string XML = "application/xml";
                //public static string TextXML = "text/xml";
                //public static string formUrlencoded = "application/x-www-form-urlencoded";
                //public static string HTML = "text/html";
                req.ContentType = "application/x-www-form-urlencoded";

                req.KeepAlive = true;

                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                //req.ContentLength = data.Length;

                //处理HttpWebRequest访问https有安全证书的问题( 请求被中止: 未能创建 SSL/TLS 安全通道。)
                ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;

                //System.Net.ServicePointManager.DefaultConnectionLimit = 50;
                //设置协议类型前设置协议版本
                req.ProtocolVersion = HttpVersion.Version11;
                //这里设置了协议类型。
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

                //  Thread.Sleep(1000);
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();

                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }

                if (resp != null)
                {
                    resp.Close();
                }
                if (req != null)
                {
                    req.Abort();
                }

                return result;
            }
            catch (Exception ex)
            {
                return result = ex.Message + "".Trim();

            }
        }
View Code

服务端

        [WebMethod]
        public string ImagToBase64(string imgbases, string WJM, string WJLX)
        {
            string err = "";
            try
            {
                string strDate = DateTime.Now.ToString("yyyyMMdd");
                string fileFullPath = "D:\\huanxin\\CarBFImg\\";//文件保存路径
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }

                //string strbase64 = imgbases.Trim().Substring(imgbases.IndexOf(",") + 1);   //将‘,’以前的多余字符串删除
                string dummyData = imgbases.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
                if (dummyData.Length % 4 > 0)
                {
                    dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                }
                MemoryStream stream = new MemoryStream(Convert.FromBase64String(dummyData));
                FileStream fs = new FileStream(fileFullPath + "\\" + WJM + WJLX, FileMode.OpenOrCreate, FileAccess.Write);
                byte[] b = stream.ToArray();
                fs.Write(b, 0, b.Length);
                fs.Close();
                return err;

            }
            catch (Exception e)
            {
                err += "\r\n异常类型: \t" + e.GetType();
                err += "\r\n异常描述:\t" + e.Message;
                err += "\r\n异常方法:\t" + e.TargetSite;
                err += "\r\n异常堆栈:\t" + e.StackTrace;

                return err;

            }
        }
View Code

 

posted @ 2022-08-03 17:58  纡ゾ少︶ㄣ  阅读(455)  评论(0编辑  收藏  举报