WCF上传下载文件

思路:上传时将要上传的文件流提交给服务器端

   下载时只需要将服务器上的流返回给客户端即可

1.契约,当需要传递的数量多于一个时就需要通过messagecontract来封装起来

这里分别实现了上传和下载的所有功能,使用流的方式来上传和下载文件

[ServiceContract]
    public interface IResource
    {
        [OperationContract]
        void Upload(FileUploadMessage stream);

        [OperationContract]
        Stream Download(string filename);
    }
    [MessageContract]
    public class FileUploadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public string resourceName;
        [MessageBodyMember(Order = 1)]
        public Stream data;
    }

2.实现

这里要注意对上传进行了异步的处理

public Stream Download(string filename)
        {
            return File.OpenRead(filename);
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="stream"></param>
        public void Upload(FileUploadMessage stream)
        {
            var path = Environment.CurrentDirectory + @"
esource";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var finalpath = path + DateTime.Now.ToString("yyyyMMddhhmmss") + stream.resourceName.Substring(stream.resourceName.LastIndexOf('\') + 1);
            //存入数据库
            var model = new Model.resourcePath();
            model.projectID = stream.projectID;
            model.statu = new BLL.ProjectBLL().GetModel(p => p.id == stream.projectID).currentStatuID;
            model.filePath = finalpath;
            model.uploadPerson = stream.uploadPerson;
            new BLL.ResourcePathBLL().Add(model);
            using (var file = File.Create(finalpath))
            {
                const int bufferlen = 1024;
                byte[] buf = new byte[bufferlen];
                int count = 0;
                while((count=stream.data.Read(buf,0,bufferlen))>0)
                {
                    file.Write(buf,0,count);
                }
            }
        }

3.配置

我们需要在配置文件中修改终结点的绑定类型为netTcpBinding类型

然后对上传的数据进行大小的限制,具体内容见下面的配置文件

<service name="Service.Resource" behaviorConfiguration="resourceBehaviors">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8755/Resource/" />
            <add baseAddress="net.tcp://localhost:8756/Resource/"/><!-- 注意此处 -->
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- 除非完全限定,否则地址相对于上面提供的基址-->
        <endpoint address="" binding="netTcpBinding" <!-- 绑定类型需要修改--> bindingConfiguration="translateBinding" 
                  contract="Service.IResource" name="ResourceService"></endpoint>
        <!-- Metadata Endpoints -->
        <!-- 元数据交换终结点供相应的服务用于向客户端做自我介绍。 -->
        <!-- 此终结点不使用安全绑定,应在部署前确保其安全或将其删除-->
        <endpoint address="mex" binding="mexHttpBinding" contract="Service.IResource" />
</service>
<!--还需要在system.system.serviceModel中添加-->
<bindings>
      <netTcpBinding><!--20M-->
        <binding name="translateBinding" maxBufferSize="20971520" maxReceivedMessageSize="20971520"
                 sendTimeout="00:30:00" transferMode="Streamed"></binding>
      </netTcpBinding>
</bindings>

客户端引用时也需要进行配置

<netTcpBinding>
        <binding name="ResourceService" transferMode="Streamed" maxBufferSize="209715200" maxReceivedMessageSize="209715200"
                 sendTimeout="00:30:00"/>
      </netTcpBinding>

4.添加服务引用

在需要的位置添加上服务引用,添加和使用方式可以看这一篇文章:WCF使用相关

5.前台调用

前台通过服务引用来调用服务,可以在这里看到服务引用怎么调用:WCF使用相关

下载
ResourceService.ResourceClient service = new ResourceService.ResourceClient("ResourceService");
            service.Open();
            Stream stream=service.Download(textBox1.Text);
            if(stream!=null)
            {
                if (stream.CanRead)
                {
                    using (FileStream fs = new FileStream(System.Environment.CurrentDirectory + 
   @"a.txt", FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLength = 4096; byte[] myBuffer = new byte[bufferLength]; int count; while ((count = stream.Read(myBuffer, 0, bufferLength)) > 0) { fs.Write(myBuffer, 0, count); } fs.Close(); stream.Close(); } } } service.Close();
上传
var service = new ResourceService.ResourceClient("ResourceService");
service.Open();
service.UploadAsync(textBox1.Text.Trim(), openFileDialog1.OpenFile());
openFileDialog1.OpenFile());
service.Close();

 上一篇:WCF使用相关

原文地址:https://www.cnblogs.com/ives/p/WCFUploadDownLoadFile.html