WCF 用netTcpbinding,basicHttpBinding 传输大文件
问题: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 传输大文件的更多相关文章
- WCF利用Stream上传大文件
WCF利用Stream上传大文件 转自别人的文章,学习这个例子,基本上wcf也算入门了,接口用法.系统配置都有了 本文展示了在asp.net中利用wcf的stream方式传输大文件,解决了大文件上传问 ...
- C# 的 WCF文章 消息契约(Message Contract)在流(Stream )传输大文件中的应用
我也遇到同样问题,所以抄下做MARK http://www.cnblogs.com/lmjq/archive/2011/07/19/2110319.html 刚做完一个binding为netTcpBi ...
- 基于RMI服务传输大文件的完整解决方案
基于RMI服务传输大文件,分为上传和下载两种操作,需要注意的技术点主要有三方面,第一,RMI服务中传输的数据必须是可序列化的.第二,在传输大文件的过程中应该有进度提醒机制,对于大文件传输来说,这点很重 ...
- linux传输大文件
http://dreamway.blog.51cto.com/1281816/1151886 linux传输大文件
- 使用QQ传输大文件
现在在公网上能传输大文件并且稳定支持断点续传的软件非常少了,可以使用qq来做这件事. qq传输单个文件有时候提示不能超过4g有时候提示不能超过60g,没搞明白具体怎么样. 可以使用qq的传输文件夹功能 ...
- TCP协议传输大文件读取时候的问题
TCP协议传输大文件读取时候的问题 大文件传不完的bug 我们在定义的时候定义服务端每次文件读取大小为10240, 客户端每次接受大小为10240 我们想当然的认为客户端每次读取大小就是10240而把 ...
- wcf综合运用之:大文件异步断点续传
在WCF下作大文件的上传,首先想到使用的就是Stream,这也是微软推荐的使用方式.处理流程是:首先把文件加载到内存中,加载完毕后传递数据.这种处理方式对小文件,值得推荐,比如几K,几十k的图片文件, ...
- rsync增量传输大文件优化技巧
问题 rsync用来同步数据非常的好用,特别是增量同步.但是有一种情况如果不增加特定的参数就不是很好用了.比如你要同步多个几十个G的文件,然后网络突然断开了一下,这时候你重新启动增量同步.但是发现等了 ...
- Samba共享传输大文件(ex:1G)失败的问题
1:问题描述 1.1 基本信息 遇见这样一个bug,路由器有USB share的功能,可将U盘内的文件通过samba和LAN端PC机中文件进行共享,测试发现小文件可正常共享,一旦文件大了(比如1G左右 ...
随机推荐
- 提高matlab运行速度和节省空间的心得
提高matlab运行速度和节省空间的心得 首先推荐使用matlab 2006a版本,该版本优点很多(不过有一个小bug,就是通过GUI自动生成的m文件居然一大堆warning,希望在已经发布了的200 ...
- Android程序的隐藏与退出
转自Android程序的隐藏与退出 Android的程序无需刻意的去退出,当你一按下手机的back键的时候,系统会默认调用程序栈中最上层Activity的Destroy()方法来销毁当前Activit ...
- lc面试准备:Reverse Bits
1 题目 Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represente ...
- Bluetooth LE(低功耗蓝牙) - 第一部分
前言 在写这篇文章的时候,谷歌刚刚发布了Android Wear ,摩托罗拉也发布了 Moto 360 智能手表.Android Wear的API还是相当基本的,是很好的文档材料,而且还会不断的更新, ...
- 【CF】304 E. Soldier and Traveling
基础网络流,增加s和t,同时对于每个结点分裂为流入结点和流出结点.EK求最大流,判断最大流是否等于当前总人数. /* 304E */ #include <iostream> #includ ...
- android逐行读取文件内容以及保存为文件
用于长时间使用的apk,并且有规律性的数据 1,逐行读取文件内容 //首先定义一个数据类型,用于保存读取文件的内容 class WeightRecord { String timestamp; flo ...
- C++中new和malloc
1.malloc的工作原理: malloc使用一个数据结构(链表)来维护分配空间链表的构成:分配的空间/上一个空间的数据/下一个空间/空间大小等信息. 对malloc分配的空间不要越界访问,因为 ...
- Two kinds of Quaternion SlerpImp (Unity)
using UnityEngine;using System.Collections; public class SlerpImp{ static float Dot(Quaternion a, Qu ...
- Django中的Form
Form 一.使用Form Django中的Form使用时一般有两种功能: 1.生成html标签 2.验证输入内容 要想使用django提供的form,要在views里导入form模块 from dj ...
- 宁波Uber优步司机奖励政策(1月18日~1月24日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...