转自别人的文章,学习这个例子,基本上wcf也算入门了,接口用法、系统配置都有了
本文展示了在asp.net中利用wcf的stream方式传输大文件,解决了大文件上传问题。主要是存档方便以后遇到该问题是来查阅。贴出部分代码,如果有疑惑或需要完整代码的请留言
WebForm1.aspx.cs
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("文件传输成功!"); }
IService1
namespace WcfService1 { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。 [ServiceContract] public interface IGetDataService { [OperationContract] void UploadFile(FileData file); } [MessageContract] public class FileData { [MessageHeader] public string filename; [MessageBodyMember] public Stream data; } }
Service1.svc
namespace WcfService1 { public class GetDataService : IGetDataService { public void UploadFile(FileData file) { FileStream fs = new FileStream("D:\\我的项目\\WcfService1\\Files\\" + 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(1024); writer.Write(buffer); } while (buffer.Length > 0); fs.Close(); file.data.Close(); } catch (Exception e) { throw new Exception(e.Message); } finally { fs.Close(); file.data.Close(); } } }
web.config
<configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <httpRuntime maxRequestLength="40960" /> </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="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" 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> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
看到有好几位同学想要源码的,我重新做了个测试工程,经测试只要网络支持,是可以上传几十M以上的大文件的
附上测试工程项目源码:https://files.cnblogs.com/easywebfactory/WcfService1.rar