WCF文件上传服务

一. 创建WCF服务

新建类库项目UpLoadFile,利用接口建立契约

  • 建立 IMtom 接口
using System.ServiceModel;
namespace UpLoadFile
{
    [ServiceContract]
   public interface IMtom
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filepath">目标路径</param>
        /// <param name="fileData">文件字节数组</param>
        [OperationContract]
        bool UploadFile(string filepath, byte[] fileData);
    }
}

  • 实现接口
using System;
using System.IO;

namespace UpLoadFile
{
    public class MyMtom : IMtom
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filepath">文件目录路径</param>
        /// <param name="fileData">文件字节数组</param>
        bool IMtom.UploadFile(string filepath, byte[] fileData)
        {
            try
            {
                FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.None);
                fs.Write(fileData, 0, fileData.Length);
                fs.Flush();
                fs.Close();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }
    }
}

二. 建立WCF宿主,配置MTOM绑定

新建控制台项目MyHost

  • 在App.config中 配置服务,特别是要在 wsHttpBinding 指定使用 Mtom
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

  <system.serviceModel>
    <services>
      <service name="UpLoadFile.MyMtom" behaviorConfiguration="Mybehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/"/>
          </baseAddresses>
        </host>
        
        <endpoint  address="UpLoadFile" bindingConfiguration="myBindingConfigration"  binding="wsHttpBinding" contract="UpLoadFile.IMtom"></endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="Mybehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <!-- wsHttpBinding 指定使用 Mtom 还是Text ,对Soap消息进行编码 -->
    <bindings>
      <wsHttpBinding>
        <binding name="myBindingConfigration"
                 messageEncoding="Mtom"
                 maxReceivedMessageSize="1073741824" 
                 receiveTimeout="00:20:00">
          <readerQuotas maxArrayLength="1073741824"/>
          
        </binding>
      </wsHttpBinding>
    </bindings>
    
  </system.serviceModel>
</configuration>
  • 在管理员模式下启动服务.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace MyHost
{
    class Program
    {
        
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(UpLoadFile.MyMtom));
            host.Open();
            Console.WriteLine("服务已经启动......");
            Console.ReadLine();
        }
    }
}

在这里插入图片描述

三. 建立上传客户端实现文件上传

项目名称 winFormClient

  • 添加服务引用
    使用**“添加服务引用”**对话框,可以添加对 Windows Communication Foundation (WCF) 服务和 WCF 数据服务 的引用。

如果您知道服务的承载地址,请在**“地址”字段中输入相应的 URL,然后单击“前往”**,以返回可用服务的列表。
在这里插入图片描述

  • 添加窗体及代码,实现文件上传.

在这里插入图片描述

using System;
using System.IO;
using System.Windows.Forms;


namespace winFormClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txtSavePath.Text = "d:\\";
        }

        private void btnUpLoad_Click(object sender, EventArgs e)
        {
            ServiceUpLoad.MtomClient mtomClient = new ServiceUpLoad.MtomClient();
            var filepath = txtSavePath.Text;
            FileInfo file = new FileInfo(txtFilePath.Text);
            byte[] bytes = File.ReadAllBytes(file.FullName);

            if (mtomClient.UploadFile(filepath + file.Name, bytes))
            {
                MessageBox.Show("上传成功");
            }
            else
            {
                MessageBox.Show("上传失败");
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = ofd.FileName;

            }
        }
    }
}

建议1000字节以上数据,使用MTOM编码传输

推荐阅读:

  1. https://www.codeproject.com/Articles/632101/Mtom-Encoding-in-WCF

2.关于MTOM 编码,msdn介绍比较详细,
https://docs.microsoft.com/zh-cn/dotnet/framework/wcf/samples/mtom-encoding

  1. https://cloud.tencent.com/developer/ask/118966
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值