Wcf 文件上傳下載

wcf 文件上傳的例子網上不少,我也是借鑑別人的示例。wcf 文件下載的示例網上就不多了,不知道是否是由於二者的處理方式比較相似,別人就沒有再上傳了。在此本人作下記錄備忘。web

UploadFile.svc.cs
public class UploadFile : IUploadFile
    {
        /// <summary>
        /// 服務器地圖文件保存路徑
        /// </summary>
        private string savePath = @"D:\礦車定位上傳地圖備份";

        /// <summary>
        /// 上傳文件
        /// </summary>
        public void UploadFileMethod(FileUploadMessage myFileMessage)
        {
            if(!Directory.Exists(savePath))//地圖存放的默認文件夾是否存在
            {
                Directory.CreateDirectory(savePath);//不存在則建立
            }

            string fileName = myFileMessage.FileName;//文件名
            string fileFullPath = Path.Combine(savePath, fileName);//合併路徑生成文件存放路徑
            Stream sourceStream = myFileMessage.FileData;

            if (sourceStream == null) { return; }
            if (!sourceStream.CanRead) { return; }

            //建立文件流,讀取流中的數據生成文件
            using (FileStream fs = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                try
                {
                    const int bufferLength = 4096;
                    byte[] myBuffer = new byte[bufferLength];//數據緩衝區
                    int count;
                    while ((count = sourceStream.Read(myBuffer, 0, bufferLength)) > 0)
                    {
                        fs.Write(myBuffer, 0, count);
                    }
                    fs.Close();
                    sourceStream.Close();
                }
                catch { return; }
            }
        }

        /// <summary>
        /// 獲取文件列表
        /// </summary>
        public string[] GetFilesList()
        {
            if(!Directory.Exists(savePath))//判斷文件夾路徑是否存在
            {
                return null;
            }

            DirectoryInfo myDirInfo = new DirectoryInfo(savePath);
            FileInfo[] myFileInfoArray = myDirInfo.GetFiles("*.zip");
            string[] myFileList = new string[myFileInfoArray.Length];
            //文件排序
            for (int i = 0; i < myFileInfoArray.Length - 1;i++ )
            {
                for (int j = i + 1; j < myFileInfoArray.Length; j++)
                {
                    if(myFileInfoArray[i].LastWriteTime > myFileInfoArray[j].LastWriteTime)
                    {
                        FileInfo myTempFileInfo = myFileInfoArray[i];
                        myFileInfoArray[i] = myFileInfoArray[j];
                        myFileInfoArray[j] = myTempFileInfo;
                    }
                }
            }

            for (int i = 0; i < myFileInfoArray.Length; i++)
            {
                myFileList[i] = myFileInfoArray[i].Name;
            }

            return myFileList;
        }

        /// <summary>
        /// 下載地圖
        /// </summary>
        public Stream DownLoadFile(string fileName)
        {
            string fileFullPath = Path.Combine(savePath, fileName);//服務器文件路徑
            if(!File.Exists(fileFullPath))//判斷文件是否存在
            {
                return null;
            }

            try
            {
                Stream myStream = File.OpenRead(fileFullPath);
                return myStream;
            }
            catch { return null; }
        }
    }

 

IUploadFile.cs

[ServiceContract]
    public interface IUploadFile
    {
        /// <summary>
        /// 上傳文件
        /// </summary>
        [OperationContract(Action = "UploadFile", IsOneWay = true)]
        void UploadFileMethod(FileUploadMessage myFileMessage);

        /// <summary>
        /// 獲取文件列表
        /// </summary>
        [OperationContract]
        string[] GetFilesList();

        /// <summary>
        /// 下載文件
        /// </summary>
        [OperationContract]
        Stream DownLoadFile(string fileName);
    }

    [MessageContract]
    public class FileUploadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public string FileName;

        [MessageBodyMember(Order = 1)]
        public Stream FileData;
    }

 

服務器端 web.config 配置文件

<service behaviorConfiguration="TramcarWcfService.UploadFileBehavior"
    name="TramcarWcfService.UploadFile">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="UploadFileBinding" contract="TramcarWcfService.IUploadFile">
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
   </service>

<basicHttpBinding>
        <binding name="UploadFileBinding" maxReceivedMessageSize="9223372036854775807" maxBufferSize="2147483647"
             sendTimeout="00:10:00" transferMode="Streamed" messageEncoding="Mtom">
          <security mode="None"/>
        </binding>
      </basicHttpBinding>
因爲個人wcf是發佈的iis上的須要添加下面的節點,用來設置上傳文件的限制大小,雖然我上傳的文件比較小,我仍是想知道上傳大文件是怎樣配置的。 <system.web><httpRuntime maxRequestLength="2097151" />
客戶端上傳文件方法

/// <summary>
        /// 上傳文件
        /// </summary>
        public void UploadFileMethod(string fileName,string fileFullPath)
        {
            UploadFile_WcfService.FileUploadMessage myFileMessage = new DataProcess.UploadFile_WcfService.FileUploadMessage();
            myFileMessage.FileName = fileName;//文件名
            using (FileStream fs = File.OpenRead(fileFullPath))
            {
                myFileMessage.FileData = fs;
                UploadFile_WcfService.IUploadFile myService = myClient.ChannelFactory.CreateChannel();
                try
                {
                    myService.UploadFileMethod(myFileMessage);
                }
                catch { }
                //關閉流
                fs.Close();
            }
        }
客戶端下載文件方法

isExit = false;//該變量是窗體是否關閉的標誌,若是窗體關閉置爲true,跳出寫文件循環
//下載地圖文件保存路徑
            string saveFilePath = saveFilePathObj.ToString();
            //從服務器中獲取地圖文件流
            Stream sourceStream = myUploadFileClass.DownloadFile(fileNameChecked);
            if (sourceStream != null)
            {
                if (sourceStream.CanRead)
                {
                    using (FileStream fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        const int bufferLength = 4096;
                        byte[] myBuffer = new byte[bufferLength];
                        int count;
                        while ((count = sourceStream.Read(myBuffer, 0, bufferLength)) > 0)
                        {
                            if (isExit == false)
                            {
                                fs.Write(myBuffer, 0, count);
                            }
                            else//窗體已經關閉跳出循環
                            {
                                break;
                            }
                        }
                        fs.Close();
                        sourceStream.Close();
                    }
                }
            }
上面的配置上傳一些比較大的文件應該是沒有問題了,若是須要下載大文件還須要在客戶端的app.config 中設置以下配置,此處的重點是設置transferMode="Streamed"默認是Buffered
,若是是Buffered是沒法設置較大的maxReceivedMessageSize="9223372036854775807"
<basicHttpBinding> <binding name="BasicHttpBinding_IUploadFile" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="9223372036854775807" messageEncoding="Mtom" textEncoding="utf-8" transferMode="Streamed" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="90000000" maxArrayLength="90000000" maxBytesPerRead="90000000" maxNameTableCharCount="90000000" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding>
相關文章
相關標籤/搜索