问题:WCF如何传输大文件

方案:主要有几种绑定方式netTcpbinding,basicHttpBinding,wsHttpbinding,设置相关的传输max消息选项,服务端和客户端都要设置,transferMode可以buffer,stream.

实例:netTcpbinding

直接代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. using System.IO;
  7. using System.Runtime.Serialization;
  8.  
  9. namespace FileWcfService
  10. {
  11. [ServiceContract(Name="KuoFileUpload",Namespace="http://www.xinvu.com/")]
  12. public interface IFileUpload
  13. {
  14.  
  15. [OperationContract]
  16. void Upload(byte[] file);
  17.  
  18. //[OperationContract] //此用于流模式
  19. //void UploadStream(FileMessage fileMessage);
  20. }
  21.  
  22. //[MessageContract]
  23. //public class FileMessage
  24. //{
  25. // [MessageHeader]
  26. // public string FileName;
  27.  
  28. // [MessageBodyMember]
  29. // public Stream FileData;
  30. //}
  31. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. using System.IO;
  7. using System.IO.Compression;
  8.  
  9. namespace FileWcfService
  10. {
  11. [ServiceBehavior(Name = "MyFileUpload")]
  12. public class FileUpload : IFileUpload
  13. {
  14. public void Upload(byte[] file)
  15. {
  16. try
  17. {
  18. Console.WriteLine(file.Length);
  19. MemoryStream ms = new MemoryStream(file);
  20. GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
  21. MemoryStream msTemp = new MemoryStream();
  22. gzip.CopyTo(msTemp);
  23. string path= @"E:\abc"+DateTime.Now.Ticks.ToString()+".rar"; //简单重命名
  24. Console.WriteLine(path);
  25. File.WriteAllBytes(path, msTemp.ToArray());
  26. }
  27. catch (Exception ex)
  28. {
  29. Console.WriteLine(ex.Message);
  30. }
  31. }
  32.  
  33. //public void UploadStream(FileMessage fileMessage)
  34. //{
  35. // string path = @"e:\" + fileMessage.FileName + DateTime.Now.Ticks.ToString() + ".rar"; // //简单重命名
  36. // try
  37. // {
  38. // FileStream fs = new FileStream(path, FileMode.CreateNew);
  39. // fileMessage.FileData.CopyTo(fs);
  40. // fs.Flush();
  41. // fs.Close();
  42. // }
  43. // catch (Exception ex)
  44. // {
  45. // Console.WriteLine(ex.Message);
  46. // }
  47. //}
  48. }
  49. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6.  
  7. namespace FileWcfService
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. using (ServiceHost host = new ServiceHost(typeof(FileUpload)))
  14. {
  15. if (host.State != CommunicationState.Opened)
  16. host.Open();
  17. Console.WriteLine("服务已启动……");
  18. Console.WriteLine();
  19. Console.Read();
  20. }
  21.  
  22. }
  23. }
  24. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.IO;
  8. using System.IO.Compression;
  9.  
  10. namespace WebApplication1
  11. {
  12. public partial class _Default : System.Web.UI.Page
  13. {
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16.  
  17. }
  18.  
  19. protected void Button1_Click(object sender, EventArgs e)
  20. {
  21. DateTime date = DateTime.Now;
  22. FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient();
  23. byte[] buffer = this.FileUpload1.FileBytes;
  24. MemoryStream ms = new MemoryStream();
  25. GZipStream zip = new GZipStream(ms, CompressionMode.Compress);
  26. zip.Write(buffer, , buffer.Length);
  27. byte[] buffer_zip = ms.ToArray();
  28. zip.Close();
  29. ms.Close();
  30. //If the file bigger than 100MB, usually, there will be fault:
  31. //Failed to allocate a managed memory buffer of 208073270 bytes. The amount of available memory may be low.
  32. //I don't know how to salve this solution.So, please use stream mode.
  33. file.Upload(buffer_zip);
  34. zip.Close();
  35. Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/> Before:" + buffer.Length + ":After" + buffer_zip.ToString() + "<br/>");
  36. Response.Write(FileUpload1.FileName);
  37.  
  38. }
  39.  
  40. protected void Button2_Click(object sender, EventArgs e)
  41. {
  42. //DateTime date = DateTime.Now;
  43. //FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient();
  44.  
  45. //FileUpload.FileMessage filedata = new FileUpload.FileMessage();
  46.  
  47. //using (MemoryStream ms = new MemoryStream())
  48. //{
  49. // filedata.FileName = this.FileUpload1.FileName;
  50. // filedata.FileData = this.FileUpload1.PostedFile.InputStream;
  51. // file.UploadStream(filedata);
  52. // Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/>");
  53. // Response.Write(FileUpload1.FileName);
  54.  
  55. //}
  56. }
  57. }
  58. }
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <system.serviceModel>
  4. <bindings>
  5. <!--
      流模式启用netTcpBindConfig,buffer启用netTcpBindingBuffer,人懒
    --> <!--<netTcpBinding>
  6. <binding name="netTcpBindConfig"
  7. closeTimeout="00:10:00"
  8. openTimeout="00:10:00"
  9. receiveTimeout="00:10:00"
  10. sendTimeout="00:10:00"
  11. transactionFlow="false"
  12. transferMode="Streamed"
  13. transactionProtocol="OleTransactions"
  14. hostNameComparisonMode="StrongWildcard"
  15. listenBacklog="10"
  16. maxBufferPoolSize="2147483647 "
  17. maxBufferSize="2147483647 "
  18. maxConnections="10"
  19. maxReceivedMessageSize="2147483647 "
  20. >
  21. <readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  22. <security mode="Transport">
  23. <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
  24. </security>
  25. </binding>
  26.  
  27. </netTcpBinding>-->
  28.  
  29. <netTcpBinding>
  30. <binding name="netTcpBindingBuffer"
  31. closeTimeout="00:10:00"
  32. openTimeout="00:10:00"
  33. receiveTimeout="00:10:00"
  34. sendTimeout="00:10:00"
  35. transactionFlow="false"
  36. transferMode="Buffered"
  37. transactionProtocol="OleTransactions"
  38. hostNameComparisonMode="StrongWildcard"
  39. listenBacklog="10"
  40. maxBufferPoolSize="2147483647 "
  41. maxBufferSize="2147483647 "
  42. maxConnections="10"
  43. maxReceivedMessageSize="2147483647 "
  44. >
  45. <readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  46. <security mode="Transport">
  47. <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
  48. </security>
  49. </binding>
  50. </netTcpBinding>
  51. </bindings>
  52. <behaviors>
  53. <serviceBehaviors>
  54. <behavior name="MyFileUpload">
  55. <serviceMetadata />
  56. <serviceDebug includeExceptionDetailInFaults="true"/>
  57. </behavior>
  58. </serviceBehaviors>
  59. </behaviors>
  60. <services>
  61. <service name="FileWcfService.FileUpload" behaviorConfiguration="MyFileUpload">
  62. <host>
  63. <baseAddresses>
  64. <add baseAddress="net.tcp://localhost:8089/FileService"/>
  65. </baseAddresses>
  66. </host>
  67. <!--<endpoint address="" binding="netTcpBinding"
  68. contract="FileWcfService.IFileUpload" bindingConfiguration="netTcpBindConfig" ></endpoint>-->
  69. <endpoint address=""
  70. binding="netTcpBinding"
  71. contract="FileWcfService.IFileUpload"
  72. bindingConfiguration="netTcpBindingBuffer" ></endpoint>
  73. <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
  74. </service>
  75. </services>
  76. </system.serviceModel>
  77. </configuration>

实例二:basicHttpBinding ,实验上传1.5G没问题,局域网

新建一个web站点,加入一个wcf data service.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.ServiceModel.Web;
  7. using System.Text;
  8. using System.IO;
  9.  
  10. namespace WcfService1
  11. {
  12. // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
  13. [ServiceContract]
  14. public interface IGetDataService
  15. {
  16. [OperationContract]
  17. void UploadFile(FileData file);
  18. }
  19. [MessageContract]
  20. public class FileData
  21. {
  22. [MessageHeader]
  23. public string filename;
  24. [MessageBodyMember]
  25. public Stream data;
  26. }
  27.  
  28. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.ServiceModel.Web;
  7. using System.Text;
  8. using System.IO;
  9.  
  10. namespace WcfService1
  11. {
  12. public class GetDataService : IGetDataService
  13. {
  14. public void UploadFile(FileData file)
  15. {
  16.  
  17. FileStream fs = new FileStream("D:\\" + file.filename, FileMode.OpenOrCreate);
  18.  
  19. try
  20. {
  21.  
  22. BinaryReader reader = new BinaryReader(file.data);
  23.  
  24. byte[] buffer;
  25.  
  26. BinaryWriter writer = new BinaryWriter(fs);
  27. long offset = fs.Length;
  28. writer.Seek((int)offset, SeekOrigin.Begin);
  29.  
  30. do
  31. {
  32.  
  33. buffer = reader.ReadBytes();
  34.  
  35. writer.Write(buffer);
  36.  
  37. } while (buffer.Length > );
  38.  
  39. fs.Close();
  40. file.data.Close();
  41.  
  42. }
  43. catch (Exception e)
  44. {
  45. throw new Exception(e.Message);
  46. }
  47. finally
  48. {
  49.  
  50. fs.Close();
  51. file.data.Close();
  52.  
  53. }
  54.  
  55. }
  56. }
  57. }
  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3. FileData file = new FileData();
  4. file.filename = FileUpload1.FileName;
  5. file.data = FileUpload1.PostedFile.InputStream;
  6. GetDataService c = new GetDataService();
  7. c.UploadFile(file);
  8. Response.Write("文件传输成功!");
  9. }
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3.  
  4. <system.web>
  5. <compilation debug="true" targetFramework="4.0" />
  6. <httpRuntime maxRequestLength="2147483647" />
  7. </system.web>
  8. <system.serviceModel>
  9. <bindings>
  10. <basicHttpBinding>
  11. <binding name="BasicHttpBinding_IGetDataService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="01:10:00" sendTimeout="01:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Streamed" useDefaultWebProxy="true">
  12. <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  13. <security mode="None">
  14. <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
  15. <message clientCredentialType="UserName" algorithmSuite="Default" />
  16. </security>
  17. </binding>
  18. </basicHttpBinding>
  19. </bindings>
  20. <client>
  21. <endpoint address="http://localhost:52884/mex" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGetDataService" contract="IGetDataService" name="BasicHttpBinding_IGetDataService" />
  22. </client>
  23. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /></system.serviceModel>
  24. <system.webServer>
  25. <modules runAllManagedModulesForAllRequests="true" />
  26. </system.webServer>
  27.  
  28. </configuration>

WCF 用netTcpbinding,basicHttpBinding 传输大文件的更多相关文章

  1. WCF利用Stream上传大文件

    WCF利用Stream上传大文件 转自别人的文章,学习这个例子,基本上wcf也算入门了,接口用法.系统配置都有了 本文展示了在asp.net中利用wcf的stream方式传输大文件,解决了大文件上传问 ...

  2. C# 的 WCF文章 消息契约(Message Contract)在流(Stream )传输大文件中的应用

    我也遇到同样问题,所以抄下做MARK http://www.cnblogs.com/lmjq/archive/2011/07/19/2110319.html 刚做完一个binding为netTcpBi ...

  3. 基于RMI服务传输大文件的完整解决方案

    基于RMI服务传输大文件,分为上传和下载两种操作,需要注意的技术点主要有三方面,第一,RMI服务中传输的数据必须是可序列化的.第二,在传输大文件的过程中应该有进度提醒机制,对于大文件传输来说,这点很重 ...

  4. linux传输大文件

    http://dreamway.blog.51cto.com/1281816/1151886 linux传输大文件

  5. 使用QQ传输大文件

    现在在公网上能传输大文件并且稳定支持断点续传的软件非常少了,可以使用qq来做这件事. qq传输单个文件有时候提示不能超过4g有时候提示不能超过60g,没搞明白具体怎么样. 可以使用qq的传输文件夹功能 ...

  6. TCP协议传输大文件读取时候的问题

    TCP协议传输大文件读取时候的问题 大文件传不完的bug 我们在定义的时候定义服务端每次文件读取大小为10240, 客户端每次接受大小为10240 我们想当然的认为客户端每次读取大小就是10240而把 ...

  7. wcf综合运用之:大文件异步断点续传

    在WCF下作大文件的上传,首先想到使用的就是Stream,这也是微软推荐的使用方式.处理流程是:首先把文件加载到内存中,加载完毕后传递数据.这种处理方式对小文件,值得推荐,比如几K,几十k的图片文件, ...

  8. rsync增量传输大文件优化技巧

    问题 rsync用来同步数据非常的好用,特别是增量同步.但是有一种情况如果不增加特定的参数就不是很好用了.比如你要同步多个几十个G的文件,然后网络突然断开了一下,这时候你重新启动增量同步.但是发现等了 ...

  9. Samba共享传输大文件(ex:1G)失败的问题

    1:问题描述 1.1 基本信息 遇见这样一个bug,路由器有USB share的功能,可将U盘内的文件通过samba和LAN端PC机中文件进行共享,测试发现小文件可正常共享,一旦文件大了(比如1G左右 ...

随机推荐

  1. 提高matlab运行速度和节省空间的心得

    提高matlab运行速度和节省空间的心得 首先推荐使用matlab 2006a版本,该版本优点很多(不过有一个小bug,就是通过GUI自动生成的m文件居然一大堆warning,希望在已经发布了的200 ...

  2. Android程序的隐藏与退出

    转自Android程序的隐藏与退出 Android的程序无需刻意的去退出,当你一按下手机的back键的时候,系统会默认调用程序栈中最上层Activity的Destroy()方法来销毁当前Activit ...

  3. lc面试准备:Reverse Bits

    1 题目 Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represente ...

  4. Bluetooth LE(低功耗蓝牙) - 第一部分

    前言 在写这篇文章的时候,谷歌刚刚发布了Android Wear ,摩托罗拉也发布了 Moto 360 智能手表.Android Wear的API还是相当基本的,是很好的文档材料,而且还会不断的更新, ...

  5. 【CF】304 E. Soldier and Traveling

    基础网络流,增加s和t,同时对于每个结点分裂为流入结点和流出结点.EK求最大流,判断最大流是否等于当前总人数. /* 304E */ #include <iostream> #includ ...

  6. android逐行读取文件内容以及保存为文件

    用于长时间使用的apk,并且有规律性的数据 1,逐行读取文件内容 //首先定义一个数据类型,用于保存读取文件的内容 class WeightRecord { String timestamp; flo ...

  7. C++中new和malloc

    1.malloc的工作原理: malloc使用一个数据结构(链表)来维护分配空间链表的构成:分配的空间/上一个空间的数据/下一个空间/空间大小等信息.    对malloc分配的空间不要越界访问,因为 ...

  8. Two kinds of Quaternion SlerpImp (Unity)

    using UnityEngine;using System.Collections; public class SlerpImp{ static float Dot(Quaternion a, Qu ...

  9. Django中的Form

    Form 一.使用Form Django中的Form使用时一般有两种功能: 1.生成html标签 2.验证输入内容 要想使用django提供的form,要在views里导入form模块 from dj ...

  10. 宁波Uber优步司机奖励政策(1月18日~1月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...