上传文件到WebService

Posted 编程猴子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传文件到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;
        }

 

以上是关于上传文件到WebService的主要内容,如果未能解决你的问题,请参考以下文章

C# winfrom将文件通过IIS(http协议)上传到服务器上

我用WebService 上传文件 想用ajax方法发送提交的文件请求 能做到吗??

如何将文件从 JavaScript 发送到 Java WebService

java Ftp上传创建多层文件的代码片段

JAVA实现WEBSERVICE 上传下载

将存储在内存中的文件上传到s3