Upload and download files using the WCF to achieve service

This article is reproduced, in accordance tutorial paper, write out a successful WCF upload and download files using the program, and now the original project and I wrote it myself upload all over

Original link: Click to open the link

This is the link I wrote example: GitHub

introduction

    Some time ago, with the WCF we did a small project, which involves uploading and downloading files. For the purpose of review and consolidate today simply sort out a bit, I sorted out, the following shows step by step how to achieve uploading and downloading of a WCF service.

Server

      1. First create a new WCF Service Library project named FileService, as shown below:

       technology sharing

      2. Service, IService rename FileService, IFileService, as shown below:

        technology sharing

      3. Open IFileService.cs, defines two methods, as follows:

technology sharing
    [ServiceContract]
    public interface IFileService
    {

        //上传文件
        [OperationContract]
        bool UpLoadFile(Stream filestream);

        //下载文件
        [OperationContract]
        Stream DownLoadFile(string downfile); 
  
    }
View Code

     4. The above method defines the input parameters and return parameters, but the actual project is often not enough, we need to increase other parameters, such as file name, file size, and the like. However, there WCF is defined as follows:

  • To retain the streaming data must parameter is the only parameter method. For example, if the stream to be processed on the input message, the operation must have exactly one input parameter. Similarly, if the output message stream processing, the operation must be exactly one output parameter or a return value.

  • Parameter and return type must be at least a  Streamthe Message  or  the IXmlSerializable .

     So we need to use Message -packaged contract characteristic parameters, modify the code as follows:

technology sharing
    [ServiceContract]
    public interface IFileService
    {
        //上传文件
        [OperationContract]
        UpFileResult UpLoadFile(UpFile filestream);

        //下载文件
        [OperationContract]
        DownFileResult DownLoadFile(DownFile downfile);
    }

    [MessageContract]
    public class DownFile
    {
        [MessageHeader]
        public string FileName { get; set; }
    }

    [MessageContract]
    public class UpFileResult
    {
        [MessageHeader]
        public bool IsSuccess { get; set; }
        [MessageHeader]
        public string Message { get; set; }
    }

    [MessageContract]
    public class UpFile
    {
        [MessageHeader]
        public long FileSize { get; set; }
        [MessageHeader]
        public string FileName { get; set; }
        [MessageBodyMember]
        public Stream FileStream { get; set; }
    }

    [MessageContract]
    public class DownFileResult
    {
        [MessageHeader]
        public long   FileSize { get; set; }
        [MessageHeader]
        public bool IsSuccess { get; set; }
        [MessageHeader]
        public string Message { get; set; }
        [MessageBodyMember]
        public Stream FileStream { get; set; }
    }
View Code

    5. Now service contract is defined, the next to achieve contract interface. Open FileService.cs file, write code that implements the server file upload and download service, as follows:

technology sharing
public class FileService : IFileService
    {
        public UpFileResult UpLoadFile(UpFile filedata)
        {

            UpFileResult result = new UpFileResult();

            string path = System.AppDomain.CurrentDomain.BaseDirectory +@"\service\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            byte[] buffer = new byte[filedata.FileSize];

            FileStream fs = new FileStream(path + filedata.FileName, FileMode.Create, FileAccess.Write);

            int count = 0;
            while ((count = filedata.FileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, count);
            }
            //清空缓冲区
            fs.Flush();
            //关闭流
            fs.Close();

            result.IsSuccess = true;

            return result;
          
        }

        //下载文件
        public DownFileResult DownLoadFile(DownFile filedata)
        {

            DownFileResult result = new DownFileResult();

            string path = System.AppDomain.CurrentDomain.BaseDirectory + @"\service\" + filedata.FileName;

            if (!File.Exists(path))
            {
                result.IsSuccess = false;
                result.FileSize = 0;
                result.Message = "服务器不存在此文件";
                result.FileStream = new MemoryStream();
                return result;
            }
            Stream ms = new MemoryStream();   
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            fs.CopyTo(ms);
            ms.Position = 0;  //重要,不为0的话,客户端读取有问题
            result.IsSuccess = true;
            result.FileSize = ms.Length;
            result.FileStream = ms;

            fs.Flush();
            fs.Close();
            return result;
        }
    }
View Code

    6. At this point, the specific implementation code completion, but we also need to configure the App.config, set the address, and binding contract. Here NetTcpBinding using binding, we also need to NetTcpBinding specific configuration, such as maxReceivedMessageSize (maximum received configuration file size), the transferMode (transmission mode, here Streamed) and the like. The final code is as follows:

technology sharing
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- 部署服务库项目时,必须将配置文件的内容添加到 
  主机的 app.config 文件中。System.Configuration 不支持库的配置文件。-->
  <system.serviceModel>
    
    <bindings>
       <netTcpBinding>
        <binding name="MyTcpBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="00:30:00" transferMode="Streamed"   >
          <security mode="None"></security>
        </binding> 
      </netTcpBinding>
    </bindings>
          
    <services>
      <service name="WcfTest.FileService">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration="MyTcpBinding" contract="WcfTest.IFileService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
             <add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfTest/Service1/" />
            <add baseAddress="net.tcp://localhost:8734/Design_Time_Addresses/WcfTest/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 为避免泄漏元数据信息,
          请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- 要接收故障异常详细信息以进行调试,
          请将以下值设置为 true。在部署前设置为 false 
            以避免泄漏异常信息-->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>
View Code

    7. Then you can run the service, if there is no problem, you will see the following screenshot.

   technology sharing

Client

  1. First create a WPF application, adding in MainWindow.xaml control, to give the following figure:

      technology sharing

     2. In the references right click and select Add Service Reference dialog box appears, we need to fill in the address of the service just opened, and then press go next, you will see the show to find the service, and then change the namespace to FileService, get As shown below.

     technology sharing

    2. After you press OK, the following references will be more of a FileService namespace, which contains just written FileServiceClient our service proxy class in a Windows Explorer, and now we can call the service through it. Write code as follows:

technology sharing
public partial class MainWindow : Window
    {

        FileServiceClient client;
        public MainWindow()
        {
            InitializeComponent();
            client = new FileServiceClient();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog Fdialog = new OpenFileDialog();

            if (Fdialog.ShowDialog().Value)
            {

                using (Stream fs = new FileStream(Fdialog.FileName, FileMode.Open, FileAccess.Read))
                {
                    string message;
                    this.filepath.Text = Fdialog.SafeFileName;
                    bool result = client.UpLoadFile(Fdialog.SafeFileName, fs.Length,fs, out message);

                    if (result == true)
                    {
                        MessageBox.Show("上传成功!");
                    }
                    else
                    {
                        MessageBox.Show(message);
                    }
                }

            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string filename = this.filename.Text;
            string path = System.AppDomain.CurrentDomain.BaseDirectory + @"\client\";
            bool issuccess=false;
            string message="";
            Stream filestream=new MemoryStream();
            long filesize = client.DownLoadFile(filename, out issuccess, out message, out filestream);

            if (issuccess)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                byte[] buffer = new byte[filesize];
                FileStream fs = new FileStream(path + filename, FileMode.Create, FileAccess.Write);
                int count = 0;
                while ((count = filestream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }

                //清空缓冲区
                fs.Flush();
                //关闭流
                fs.Close();
                MessageBox.Show("下载成功!");

            }
            else
            {

                MessageBox.Show(message);
            
            }


        }
    }
View Code

 

   3. Run the program, upload and download files, will be at the server locate the file uploads and downloads are under the directory file and run the customer service side, the test passes. Interface is as follows:

   technology sharingtechnology sharing

summary

  This paper describes the graphic step by step how to upload and download files function, which involves the WCF is actually a lot of knowledge, but the heart is too simple. If there do not understand, you can access Google, Baidu, you can also leave a message. If you have better suggestions, please feel free, grateful!


Reproduced in: https: //my.oschina.net/dongri/blog/610908

Guess you like

Origin blog.csdn.net/weixin_33711641/article/details/91765910