问题:WCF如何传输大文件

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

实例:netTcpbinding

直接代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IO;
using System.Runtime.Serialization; namespace FileWcfService
{
[ServiceContract(Name="KuoFileUpload",Namespace="http://www.xinvu.com/")]
public interface IFileUpload
{ [OperationContract]
void Upload(byte[] file); //[OperationContract] //此用于流模式
//void UploadStream(FileMessage fileMessage);
} //[MessageContract]
//public class FileMessage
//{
// [MessageHeader]
// public string FileName; // [MessageBodyMember]
// public Stream FileData;
//}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IO;
using System.IO.Compression; namespace FileWcfService
{
[ServiceBehavior(Name = "MyFileUpload")]
public class FileUpload : IFileUpload
{
public void Upload(byte[] file)
{
try
{
Console.WriteLine(file.Length);
MemoryStream ms = new MemoryStream(file);
GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream msTemp = new MemoryStream();
gzip.CopyTo(msTemp);
string path= @"E:\abc"+DateTime.Now.Ticks.ToString()+".rar"; //简单重命名
Console.WriteLine(path);
File.WriteAllBytes(path, msTemp.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} //public void UploadStream(FileMessage fileMessage)
//{
// string path = @"e:\" + fileMessage.FileName + DateTime.Now.Ticks.ToString() + ".rar"; // //简单重命名
// try
// {
// FileStream fs = new FileStream(path, FileMode.CreateNew);
// fileMessage.FileData.CopyTo(fs);
// fs.Flush();
// fs.Close();
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }
//}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel; namespace FileWcfService
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(FileUpload)))
{
if (host.State != CommunicationState.Opened)
host.Open();
Console.WriteLine("服务已启动……");
Console.WriteLine();
Console.Read();
} }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.IO.Compression; namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void Button1_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient();
byte[] buffer = this.FileUpload1.FileBytes;
MemoryStream ms = new MemoryStream();
GZipStream zip = new GZipStream(ms, CompressionMode.Compress);
zip.Write(buffer, , buffer.Length);
byte[] buffer_zip = ms.ToArray();
zip.Close();
ms.Close();
//If the file bigger than 100MB, usually, there will be fault:
//Failed to allocate a managed memory buffer of 208073270 bytes. The amount of available memory may be low.
//I don't know how to salve this solution.So, please use stream mode.
file.Upload(buffer_zip);
zip.Close();
Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/> Before:" + buffer.Length + ":After" + buffer_zip.ToString() + "<br/>");
Response.Write(FileUpload1.FileName); } protected void Button2_Click(object sender, EventArgs e)
{
//DateTime date = DateTime.Now;
//FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient(); //FileUpload.FileMessage filedata = new FileUpload.FileMessage(); //using (MemoryStream ms = new MemoryStream())
//{
// filedata.FileName = this.FileUpload1.FileName;
// filedata.FileData = this.FileUpload1.PostedFile.InputStream;
// file.UploadStream(filedata);
// Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/>");
// Response.Write(FileUpload1.FileName); //}
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<!--
  流模式启用netTcpBindConfig,buffer启用netTcpBindingBuffer,人懒
--> <!--<netTcpBinding>
<binding name="netTcpBindConfig"
closeTimeout="00:10:00"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
transactionFlow="false"
transferMode="Streamed"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
listenBacklog="10"
maxBufferPoolSize="2147483647 "
maxBufferSize="2147483647 "
maxConnections="10"
maxReceivedMessageSize="2147483647 "
>
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding> </netTcpBinding>--> <netTcpBinding>
<binding name="netTcpBindingBuffer"
closeTimeout="00:10:00"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
transactionFlow="false"
transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
listenBacklog="10"
maxBufferPoolSize="2147483647 "
maxBufferSize="2147483647 "
maxConnections="10"
maxReceivedMessageSize="2147483647 "
>
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyFileUpload">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="FileWcfService.FileUpload" behaviorConfiguration="MyFileUpload">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8089/FileService"/>
</baseAddresses>
</host>
<!--<endpoint address="" binding="netTcpBinding"
contract="FileWcfService.IFileUpload" bindingConfiguration="netTcpBindConfig" ></endpoint>-->
<endpoint address=""
binding="netTcpBinding"
contract="FileWcfService.IFileUpload"
bindingConfiguration="netTcpBindingBuffer" ></endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
</service>
</services>
</system.serviceModel>
</configuration>

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO; namespace WcfService1
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
[ServiceContract]
public interface IGetDataService
{
[OperationContract]
void UploadFile(FileData file);
}
[MessageContract]
public class FileData
{
[MessageHeader]
public string filename;
[MessageBodyMember]
public Stream data;
} }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO; namespace WcfService1
{
public class GetDataService : IGetDataService
{
public void UploadFile(FileData file)
{ FileStream fs = new FileStream("D:\\" + file.filename, FileMode.OpenOrCreate); try
{ BinaryReader reader = new BinaryReader(file.data); byte[] buffer; BinaryWriter writer = new BinaryWriter(fs);
long offset = fs.Length;
writer.Seek((int)offset, SeekOrigin.Begin); do
{ buffer = reader.ReadBytes(); writer.Write(buffer); } while (buffer.Length > ); fs.Close();
file.data.Close(); }
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{ fs.Close();
file.data.Close(); } }
}
}
     protected void Button1_Click(object sender, EventArgs e)
{
FileData file = new FileData();
file.filename = FileUpload1.FileName;
file.data = FileUpload1.PostedFile.InputStream;
GetDataService c = new GetDataService();
c.UploadFile(file);
Response.Write("文件传输成功!");
}
<?xml version="1.0" encoding="utf-8"?>
<configuration> <system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<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">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:52884/mex" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGetDataService" contract="IGetDataService" name="BasicHttpBinding_IGetDataService" />
</client>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" /></system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer> </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. BZOJ 3569 DZY Loves Chinese II

    Description 神校XJ之学霸兮,Dzy皇考曰JC. 摄提贞于孟陬兮,惟庚寅Dzy以降. 纷Dzy既有此内美兮,又重之以修能. 遂降临于OI界,欲以神力而凌♂辱众生. 今Dzy有一魞歄图,其上 ...

  2. 如何监控 Nginx?

    什么是 Nginx? Nginx("engine-x")是一个 HTTP 和反向代理服务器,同时也是一个邮件代理服务器和通用的 TCP 代理服务器.作为一个免费开源的服务器,Ngi ...

  3. 关于spring3中No Session found for current thread!and Transaction的配置和管理(转)

    今天我是特别的郁闷,本来项目做到一半,以前都好好的,结果下午就出现问题,苦逼的到现在才解决.它出现问题的时候都一声不坑, ,(天啦,现在才发现CSDN啥时候把QQ表情给整过来了)就在注册用户的时候,咦 ...

  4. 如何快速使用ECharts绘制可视化图表

    1.在ECharts官网,下载ECharts的源码和示例文件. 2.解压缩下载下来的Echars压缩包,找到doc\example\www\echartsjs目录,将里面的js文件全部取出来,放到项目 ...

  5. C/C++中程序在使用堆内存时的内存复用问题

    在一个C/C++程序中,如果使用了堆内存的管理机制,那么内存究竟是怎么分配与回收的呢? 先看一个程序: #include <iostream> using namespace std; i ...

  6. 【转】XCode快捷键

    原文网址:http://www.cnblogs.com/yjmyzz/archive/2011/01/25/1944325.html 1. 文件 CMD + N: 新文件CMD + SHIFT + N ...

  7. Apache 整合 Tomcat (首先Apache 发布的是PHP项目,占用端口80,tomcat 发布的是Java 项目,占用端口8080)

    情况简介: Apache 整合 Tomcat (首先Apache 发布的是PHP项目,占用端口80,tomcat 发布的是Java 项目,占用端口8080),而现在是虚拟出来两个域名(希望这两个域名都 ...

  8. Alfred(未完待续)

    之前曾经有写过一篇QuickSilver的博文,大力称赞它是Mac下的神器,但是现在,QS光荣下岗了,因为我找到了另外一款比QS更加好用,更加神器的APP:Alfred小帽子. 软件名:Alfred ...

  9. UCloud EIP 你真的懂得如何使用么? - SegmentFault

    UCloud EIP 你真的懂得如何使用么? - SegmentFault UCloud EIP 你真的懂得如何使用么?

  10. Intersection - POJ 1410(线段与矩形是否相交)

    题目大意:给一个线段和一个矩形,判断线段是否和矩形有公共点.   分析:用矩形的四个边当线段判断与所给的线段是否有交点,需要注意的是给的矩形是不标准的,需要自己转换,还需要注意线段有可能在矩形内部. ...