Upload and download file service with WCF implementation

Source: Internet
Author: User
Tags ftp file

  before WCF did not appear, I have been using WebService to upload files, I do not know why others to do so, because our file server and website backstage and the site front desk is not the same machine, operators feel that ftp file is too troublesome, I will be a dedicated to upload files WebService, put this webservice deployed on the file server, and then call this webservice in the background of the website, the Web page uploaded to the background of the file into bytes passed to the WebService, Then webservice the stream to save the file to a site that only allows static pages (static sites can prevent some script Trojans). WebService to upload files There is a problem is inefficient, and can not transfer large data volumes of files, of course, you can use the Mtom in WSE to transfer large files, with WCF is much better, by using WCF pass stream object to pass the big data file, but there are some limitations:

1 . Only BasicHttpBinding, nettcpbinding, and netnamedpipebinding support transfer stream data.

2. The stream data type must be a serializable stream or MemoryStream.

3. The message body cannot contain other data when it is delivered.

4, Transfermode restrictions and maxreceivedmessagesize restrictions.

The following specific implementation: Create a new Wcfservice, the code of the interface file is as follows:

{
[OperationContract (Action="UploadFile", IsOneWay=True)]
voidUploadFile (Fileuploadmessage request);
}


[MessageContract]
PublicClassFileuploadmessage
{
[MessageHeader (MustUnderstand=True)]
PublicString savepath;

        [messageheader (mustunderstand  = true)]
        public  string  FileName;

        [messagebodymember (order  = 1)]
        public  stream filedata;

     {
         [operationcontract (Action =  "uploadfile" Span style= "color: #000000;" >, isoneway =  true)]
        void  uploadfile (Fileuploadmessage request);
    }

[ServiceContract] public interface Iuploadservice {[OperationContract (Action = "UploadFile", IsOneWay = t     Rue)] void UploadFile (Fileuploadmessage request); }

[MessageContract] public class Fileuploadmessage {[MessageHeader (MustUnderstand = true)] public s Tring Savepath;

[MessageHeader (MustUnderstand = True)] public string FileName;

[Messagebodymember (Order = 1)] public Stream FileData;

}

The purpose of defining the Fileuploadmessage class is because the third limit, otherwise the file name and the storage path can not be passed to WCF, according to the second limit, the document data is passed by System.IO.Stream

interface method Only one, is to upload files, note that the method parameter is Fileuploadmessage

The code for the interface implementation class file is as follows:

public class Uploadservice:iuploadservice     {        public void UploadFile (Fileuploadmessage request)         {             string uploadfolder = @ "C:\kkk\";             string savapath = Request. Savepath;             string datestring = DateTime.Now.ToShortDateString () + @ "\";             string fileName = Request. FileName;             Stream sourcestream = Request. FileData;             FileStream targetstream = null;                         if (!sourcestream.canread)             {                 throw new Exception ("Unreadable data stream!");            }              if (Savapath = = null) Savapath = @ "photo\";             if (!savapath.endswith ("\ \")) Savapath + = "\";

Uploadfolder = Uploadfolder + Savapath + datestring; if (!             Directory.Exists (Uploadfolder)) {directory.createdirectory (Uploadfolder); }

            string filePath = Path.Combine (Uploadfolder, FileName);             using (Targetstream = new FileStream (FilePath, FileMode.Create, FileAccess.Write, Fileshare.none)              {               //read from the Input stream in 4K chunks                 //and save to output stream                  const int bufferlen = 4096;                 byte[] buffer = new byte [Bufferlen];                 int count = 0;                 while ((count = sourcestream.read (buffer, 0, Bufferlen)) > 0)                 {                     Targetstream.write (buffer, 0, count);                }                  Targetstream.close ();                 Sourcestream.close () ;            }        }

}

The implementation of the function is to the specified directory by the date of the directory partition, and then the file name is passed to save the files.

The most important part of this article is the following Web. config configuration:

<System.ServiceModel>
<Bindings>
<BasicHttpBinding>
<BindingName= "Filetransferservicesbinding"MaxReceivedMessageSize= "9223372036854775807"
Messageencoding= "Mtom"Transfermode= "Streamed"Sendtimeout= "00:10:00"/>
</BasicHttpBinding>
</Bindings>
<Services>
<ServiceBehaviorconfiguration= "Uploadwcfservice.uploadservicebehavior"
Name= "Uploadwcfservice.uploadservice">
<EndpointAddress=""Binding= "BasicHttpBinding"Bindingconfiguration= "Filetransferservicesbinding"Contract= "Uploadwcfservice.iuploadservice">
</Endpoint>
<EndpointAddress= "Mex"Binding= "mexHttpBinding"Contract= "IMetadataExchange"/>
</Service>
</Services>
<Behaviors>
<Servicebehaviors>
<BehaviorName= "Uploadwcfservice.uploadservicebehavior">
<ServicemetadataHttpgetenabled= "true"/>
<ServicedebugIncludeexceptiondetailinfaults= "false" />
</Behavior>
</servicebehaviors>
</Behaviors>
</system.servicemodel>

can only pass 4m The file, so in <System.Web >< httpruntime maxrequestlength =2097151 "/>

This completes the Wcfservice, creating a new console project or a Web project to test. Note that the client side configuration must be the same as the server, the instance program is downloaded here.

Upload and download file service with WCF implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.