上傳檔案到WebService

來源:互聯網
上載者:User

標籤:user   static   esc   請求   null   exce   epo   ict   mat   

用戶端代碼

  先把檔案進行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;        }

 

上傳檔案到WebService

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.