将图片二进制流上传到服务器

代码...

        /// <summary>
        /// 调用webservice将图片的二进制流上传到服务器
        /// </summary>
        /// <param name="url">上传图片的服务地址</param>
        /// <param name="file"></param>
        /// <param name="pic">文件的二进制流</param>
        /// <param name="paramName">名称...我这里填"file"就没错了,,,,</param>
        /// <param name="contentType">contentType的值(这里传的是图片类型为:image/jpeg)</param>
        /// <param name="nvc">键值对,Webservice服务哪里需要的其它数据,比如上传的用户ID及其他信息</param>
        /// <returns></returns>
        public static string HttpUploadFile(string url,string file,byte[] pic, string paramName, string contentType, NameValueCollection nvc)
        {
            string result = string.Empty;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Method = "POST";
            req.KeepAlive = true;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
            req.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream writeStream = req.GetRequestStream();
            
            foreach (string key in nvc.Keys)
            {
                writeStream.Write(boundarybytes, 0, boundarybytes.Length);
                //string formitem = string.Format(formdataTemplate, key, nvc[key]);
                string formdataTemplate = "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + nvc[key];
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
                writeStream.Write(formitembytes, 0, formitembytes.Length);
            }
            writeStream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\""+paramName+"\"; filename=\""+file+"\"\r\nContent-Type: "+contentType+"\r\n\r\n";
            //string header = string.Format(headerTemplate, paramName, file, contentType);         
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(headerTemplate);
            writeStream.Write(headerbytes, 0, headerbytes.Length);
            writeStream.Write(pic, 0, pic.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            writeStream.Write(trailer, 0, trailer.Length);
            writeStream.Close();

            WebResponse response = null;
            try
            {
                response = req.GetResponse();
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }               
            }
            catch (Exception ex)
            {
                result = ex.Message;     
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (writeStream != null)
                {
                    writeStream.Close();
                    writeStream = null;
                }
                if(req!=null)
                req = null;
            }

            return result;
        }
View Code

调用代码...

byte[] pic = getImage(picUrl.Key,picUrl.Value, HttpTimeOut);
string PicUploadUrl ="{webservice路径}";
NameValueCollection nvc = new NameValueCollection();
nvc.Add("example_upload_user_id", "007");
string ret = UploadPic.HttpUploadFile(PicUploadUrl, "picname.jpg",pic, "file", "image/jpeg", nvc);

附加代码...将指定路径的图片转换为二进制流

        public static byte[] getImage(string imageUrl, string picType, int HttpTimeOut)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                Uri uri = new Uri(imageUrl);
                byte[] buffer = new byte[1 * 1000 * 1024];
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Timeout = HttpTimeOut;
                request.Method = "GET";
                request.ContentType = "image/" + picType;
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                response = (HttpWebResponse)request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        buffer = new Byte[1024];
                        int current = 0;
                        while ((current = stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            ms.Write(buffer, 0, current);
                        }
                        return ms.ToArray();
                    }
                }
                /******************************下面这种方式下载图片不完全*********************************/
                //using (Stream receiveStream = response.GetResponseStream()) // 网络stream, 不可获取长度
                //{   
                //    //BinaryReader reader = new BinaryReader(receiveStream);                                     
                //    bytesRead = receiveStream.Read(buffer, 0, buffer.Length);               
                //}
                //bytesProcessed += bytesRead;                                            
                //byte[] bytes = new byte[bytesProcessed];
                //Buffer.BlockCopy(buffer, 0, bytes, 0, bytesProcessed);
                //return bytes;

            }
            catch
            {
                return new byte[0];

            }
            finally
            {
                if (response != null) //如果服务器未响应,那么继续等待相应
                {
                    response.Close();
                    response = null;
                }
                if (request == null)
                {
                    request = null;
                }
            }
        }
View Code

 

 

感谢我的搭档:lq筒靴...

 

posted @ 2016-11-12 22:43  zh89233  阅读(8903)  评论(0编辑  收藏  举报