wcf以post的形式上传大数据附加上传其他的信息

由于wcf的特殊要求,iis寄宿的形式有那么个稍微麻烦的缺点就是如果函数的参数定义为stream的话就只能包含一个参数,那么其他的数据该如何上传呢?


[OperationContract, WebInvoke(Method = "POST", UriTemplate = "uploadicon",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
       ResponseFormat = WebMessageFormat.Json,
       RequestFormat = WebMessageFormat.Json)]
        upload uploadicon(Stream iconimg);

函数的参数就只能这样写了(upload,是我自己写的数据契约,可以改成sting 类型)

如果写成

  upload uploadicon(Stream iconimg,string nie);
那么就会报错



来点聪明的办法,这不是为发明的,只是无意间看到其他人博客写的这种方法,也确实不错

先普及一下知识http的协议格式

看看这位大神的博客就知道了

http://blog.csdn.net/zhaoneiep/article/details/5487133


我这里利用的是http的头部来传递信息:

具体的函数是这样的


  WebHeaderCollection headerCollection = WebOperationContext.Current.IncomingRequest.Headers;
            //获得http头编码
            string item = "userid";
            string value = headerCollection.Get(item);


请注意:http协议头部中不能包含中文,要是想要用中文就要用中文转换成utf-8的格式再进行传输,我试过,头部可以带好多文字啊,但是为了保险起见,限定一下字数也是必要的

贴出整个函数以供欣赏


 public upload uploadicon(Stream iconimg)
        {
            upload ul = new upload();
            WebHeaderCollection headerCollection = WebOperationContext.Current.IncomingRequest.Headers;
            //获得http头编码
            string item = "userid";
            string value = headerCollection.Get(item);

          //初始化http的类
 /*         WebHeaderCollection headerCollection = WebOperationContext.Current.IncomingRequest.Headers;
            //获得http头编码
            string item = "command";
            string value = headerCollection.Get(item);
            ///url utf-8解码
            value=System.Web.HttpUtility.UrlDecode(value, System.Text.Encoding.UTF8); 
          
     */


              try
            {
                //创建文件
                using (FileStream outputStream = new FileStream(@"F:\1\+" + value + ".jpg", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    ///网络流转字符流
                    // 我们不用对两个流对象进行读写,只要复制流就OK  
                    iconimg.CopyTo(outputStream);
                    写入文件,清除缓冲区
                    outputStream.Flush();

                }
            }

            catch (Exception e)
            {
                //捕捉错误,转换成为字节流
                ul.issuccess = -1;
            }
            //发送成功的信息,转换成字节流
            string connstr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SqlConnStr"].ConnectionString;数据库连接字符串
            SqlConnection con = new SqlConnection(connstr);
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = con;

            try
            {
                con.Open();
            }
            catch
            {
                ul.issuccess = -1;
                return ul;
            }
            cmd.CommandText = "UPDATE dbo.T_Users SET ICON = N'" + value + ".jpg' WHERE UserID=" + value + ";";
            SqlDataReader dr = cmd.ExecuteReader();
            ul.issuccess = 1;
            return ul;
        }
    }

还有一个:就是如何在头部添加这些信息:

以下是客户端的的程序


 //发送图片
        void sendpic()
        {

            //utf8编码
            string chin = "你好啊啊啊";
            ///从中文字符串转换成utf-8的字符串
            string urlutf8 = System.Web.HttpUtility.UrlEncode(chin); 
          


            //发送协议初始化
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:49038/Service1.svc/hello");
            request.Method = "POST";
            request.ContentType = "text/plain";
            request.Headers.Add("userid", "123456");///添加头信息
            request.Headers.Add("command", urlutf8);///添加头信息
            try
            {
                //上传文件
              
                try
                {
                   
                    string fileName = @"C:\Users\nie\Desktop\时间都去哪儿了.mp3";
                    FileStream fs = null;
                    fs = new FileStream(fileName, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                    ///在图片的二进制码中插入用户信息
                    int streamLength = (int)fs.Length;
                    byte[] buffer = new byte[streamLength + 4];

                    byte[] data = new byte[4];
                    UInt32 myid = 1234565;
                    data = BitConverter.GetBytes(myid);
                    for (int xixi = 0; xixi < 4; xixi++)
                        buffer[xixi] = data[xixi];
                    fs.Read(buffer, 4, streamLength);

                    //发送图片和用户信息
                    request.ContentLength = buffer.Length;
                    Stream requestStram = request.GetRequestStream();
                    requestStram.Write(buffer, 0, buffer.Length);
                    requestStram.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    Console.WriteLine("失败");
                    Console.Read();
                    return;
                }
                Console.WriteLine("完成");




                //收到回复
                Stream getStream = request.GetResponse().GetResponseStream();

                byte[] resultByte = new byte[1000];
                getStream.Read(resultByte, 0, resultByte.Length);

                Console.WriteLine(Encoding.UTF8.GetString(resultByte));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值