当前位置: 首页 > news >正文

用Restful方式调用WCF进行上传下载(转)

http://www.cnblogs.com/jillzhang/archive/2008/07/14/1242939.html

在 前面几篇文章中,分别就WCF如何与Ajax交互,如何返回json数据给Ajax,如何为ExtJs控件提供数据,如何用Http的访问方式异步调用 Restful的WCF服务,本文着重讲述如何用Restful方式调用WCFl进行文件的上传和下载。在前面的文章中,曾经写过Restful的WCF 支持两种格式的请求和响应的数据格式:1)XML 2) JSON。事实上WCF不光支持上述两种格式,它还支持原生数据(Raw,来源于Carlos' blog)。 这样一来,WCF的Restful方式实际上支持任意一种格式的,因为原生的即表明可以是任意一种格式,WCF从客户端到服务端,从服务端到客户端都会保 持这种数据的原来的数据格式。通过查阅MSDN中WebMessageEncodingBindingElement 类的说明:也能找到上述的论证

首 先总结一下如何在Restful的WCF的服务端和客户端传递原生的数据(Raw),在WCF中,返回值或者参数为System.IO.Stream或者 System.IO.Stream的派生类型的时候,加配上HTTP请求和Restful服务操作响应消息中的ContentType,便能实现原生数据 的传输。

下面通过一个上传和下载图片文件的项目示例来演示如上的结论。

第一步:在VS2008中,创建一个解决方案:WcfBinaryRestful,包括四个项目:如下图所示:

其中各个项目的说明如下表所述:

项目名称

说明

WcfBinaryRestful.Contracts

WCF服务的契约部分

WcfBinaryRestful.Service

WCF服务具体实现部分

WcfBinaryRestful.Host

WCF服务的Console程序的承载程序

WcfBinaryRestful.Client

客户端

 
第二步:在WcfBinaryRestful.Contracts中创建并设计服务契约IService.cs,代码如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WcfBinaryRestful.Contracts
{
    [ServiceContract]
    
public interface IService
    
{
        [OperationContract]
        System.IO.Stream ReadImg();

        [OperationContract]
        
void ReceiveImg(System.IO.Stream stream);
        
    }

}

其中ReadImg方法用于提供jpg图片文件,供客户端下载,而ReceiveImg用于接收客户端上传的jpg图片

第三步:在WcfBinaryRestful.Service项目中创建并设计服务具体实现类:Service.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Web;
using System.Drawing;
using System.Diagnostics;

namespace WcfBinaryRestful.Service
{
    
public class Service : Contracts.IService
    
{
        [WebInvoke(Method 
= "*", UriTemplate = "ReadImg")]
        
public System.IO.Stream ReadImg()
        
{
            
string runDir = System.Environment.CurrentDirectory;
            
string imgFilePath = System.IO.Path.Combine(runDir, "jillzhanglogo.jpg");
            System.IO.FileStream fs 
= new System.IO.FileStream(imgFilePath, System.IO.FileMode.Open);
            System.Threading.Thread.Sleep(
2000);
            WebOperationContext.Current.OutgoingResponse.ContentType 
= "image/jpeg";
            
return fs;
        }

        [WebInvoke(Method 
= "*", UriTemplate = "ReceiveImg")]
       
public  void ReceiveImg(System.IO.Stream stream)
        
{
            Debug.WriteLine(WebOperationContext.Current.IncomingRequest.ContentType);
            System.Threading.Thread.Sleep(
3000);
            
string runDir = System.Environment.CurrentDirectory;
            
string imgFilePath = System.IO.Path.Combine(runDir, "ReceiveImg.jpg");
            Image bmp 
= Bitmap.FromStream(stream);
            bmp.Save(imgFilePath);
        }

    }

}

第四步:用配置的方式,创建服务承载项目:WcfBinaryRestful.Host。并使得服务可以用Restful方式访问。

Host.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WcfBinaryRestful.Host
{
    
public class Host
    
{
        
static void Main()
        
{
            
using (ServiceHost host = new ServiceHost(typeof(Service.Service)))
            
{
                host.Open();
                Console.WriteLine(
"服务已经启动!");
                Console.Read();
            }

        }

    }

}

App.config


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    
<system.serviceModel>
        
<services>
            
<service name="WcfBinaryRestful.Service.Service">
                
<host>
                    
<baseAddresses>
                        
<add baseAddress="http://127.0.0.1:9874/"/>
                    
</baseAddresses>
                
</host>
                
<endpoint address="" binding="webHttpBinding" contract="WcfBinaryRestful.Contracts.IService" behaviorConfiguration="WcfBinaryRestfulBehavior"></endpoint>
            
</service>
        
</services>
        
<behaviors>
            
<endpointBehaviors>
                
<behavior name="WcfBinaryRestfulBehavior">
                    
<webHttp/>
                
</behavior>
            
</endpointBehaviors>
        
</behaviors>
    
</system.serviceModel>
</configuration>

第五步:实现客户端程序

Form1.cs

 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WcfBinaryRestful.Client
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }

        System.Net.WebClient wc;
        
private void button1_Click(object sender, EventArgs e)
        
{
            wc 
= new System.Net.WebClient();

            SaveFileDialog op 
= new SaveFileDialog();
            
if (op.ShowDialog() == DialogResult.OK)
            
{
                wc.DownloadFileAsync(
new Uri("http://127.0.0.1:9874/ReadImg"), op.FileName);
                wc.DownloadFileCompleted 
+= new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                button2.Enabled 
= true;
                button1.Enabled 
= false;
            }


        }


        
void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        
{
            
if (e.Cancelled)
            
{
                button2.Enabled 
= false;
                button1.Enabled 
= true;
                MessageBox.Show(
"用户已经取消下载!");
                
return;
            }

            
using (System.Net.WebClient wc = e.UserState as System.Net.WebClient)
            
{
                button2.Enabled 
= false;
                button1.Enabled 
= true;
                MessageBox.Show(
"下载完毕!");
            }

        }


        
private void button2_Click(object sender, EventArgs e)
        
{
            
if (wc != null)
            
{
                wc.CancelAsync();
            }

        }


        System.Net.WebClient uploadWc 
= new System.Net.WebClient();
        
private void button3_Click(object sender, EventArgs e)
        
{
            OpenFileDialog op 
= new OpenFileDialog();
            op.Filter 
= "jpg文件(*.jpg)|*.jpg";
            
if (op.ShowDialog() == DialogResult.OK)
            
{
                uploadWc.Headers.Add(
"Content-Type""image/jpeg");
                System.IO.FileStream fs 
= new System.IO.FileStream(op.FileName,System.IO.FileMode.Open);
                
byte[] buffer = new byte[(int)fs.Length];
                fs.Read(buffer, 
0, (int)fs.Length);
                fs.Close();
                uploadWc.UploadDataCompleted 
+= new System.Net.UploadDataCompletedEventHandler(uploadWc_UploadDataCompleted);
                uploadWc.UploadDataAsync(
new Uri("http://127.0.0.1:9874/ReceiveImg"), buffer);
                button3.Enabled 
= false;
                button4.Enabled 
= true;
            }

        }


        
void uploadWc_UploadDataCompleted(object sender, System.Net.UploadDataCompletedEventArgs e)
        
{
            
if (e.Cancelled)
            
{
                button3.Enabled 
= true;
                button4.Enabled 
= false;
                MessageBox.Show(
"用户已经取消上传!");
                
return;
            }

            MessageBox.Show(
"完成上传!");
            button3.Enabled 
= true;
            button4.Enabled 
= false;
        }


        
private void button4_Click(object sender, EventArgs e)
        
{
            uploadWc.CancelAsync();
        }


     
    }

}

设置好多启动项目调试后,调试,出现如下的运行界面:

1.服务承载程序运行界面图:

2.客户端运行界面图:

点击开始下载按钮,选择一个下载文件的保存位置,等待一会后,会提示下载成功,如下图所示:

打开刚才选择下载文件的保存位置,便能发现已经成功下载了jpg的图片文件:

当然顺便还可以温习一下如何异步调用Restful的WCF服务,点击取消下载可以停止下载,不再多说

点击开始上传,选择一个要上传的jpg图片,等待几秒钟,便能收到上传成功的对话框,如下图所示:

找到服务承载程序所在目录,便能看到上传的jpg图像文件:

相关文章:

  • 飞雪桌面日历注册码
  • 趋势科技:Web2.0网站将成黑客首要攻击目标
  • 最老程序员创业札记:全文检索、数据挖掘、推荐引擎应用42
  • CENTOS NTFS支持
  • SSD固态硬盘解析和部署注意事项
  • Visual Studio 2010 中的代码约定设置
  • DevExpress ASPxGridView 使用方法概述
  • SQL2005 数据的导出 bcp 命令
  • .NET正则基础之——正则委托
  • 微“.NET研究”软“重启”Windows Phone 7 设计的经过
  • XML各层对象的方法
  • weblogic 10.3 for redhat 5.5 install
  • SELinux进阶篇 应用目标策略管理非限制进程和用户
  • EM智能会议室预订系统
  • ASP.NET经典源代码下载地址及数据库配置方法
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • Linux编程学习笔记 | Linux IO学习[1] - 文件IO
  • MySQL几个简单SQL的优化
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 从伪并行的 Python 多线程说起
  • 关键词挖掘技术哪家强(一)基于node.js技术开发一个关键字查询工具
  • 前端设计模式
  • 如何利用MongoDB打造TOP榜小程序
  • 微信支付JSAPI,实测!终极方案
  • 新书推荐|Windows黑客编程技术详解
  • 移动端唤起键盘时取消position:fixed定位
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • Prometheus VS InfluxDB
  • 东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
  • 哈罗单车融资几十亿元,蚂蚁金服与春华资本加持 ...
  • #include
  • #ubuntu# #git# repository git config --global --add safe.directory
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • $.proxy和$.extend
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (175)FPGA门控时钟技术
  • (4)STL算法之比较
  • (52)只出现一次的数字III
  • (Redis使用系列) Springboot 整合Redisson 实现分布式锁 七
  • (zt)最盛行的警世狂言(爆笑)
  • (八)五种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (定时器/计数器)中断系统(详解与使用)
  • (附源码)spring boot基于小程序酒店疫情系统 毕业设计 091931
  • (简单有案例)前端实现主题切换、动态换肤的两种简单方式
  • (四)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (五)网络优化与超参数选择--九五小庞
  • (学习日记)2024.03.25:UCOSIII第二十二节:系统启动流程详解
  • (一)基于IDEA的JAVA基础1
  • (转)原始图像数据和PDF中的图像数据
  • .NET Core工程编译事件$(TargetDir)变量为空引发的思考
  • .net core使用RPC方式进行高效的HTTP服务访问