Upload and download files through Web Services

Source: Internet
Author: User

With the development of Internet technology and the increasing demand for cross-platform services, Web Services is widely used. We need to pass string information through web services and binary file information. Next, we will introduce how to download files from the server to the client through Web Services and upload files from the client to the server through Web Services.

1. Display and download files through Web Services

The Web Services created here are named getbinaryfile, which provides two common methods: getimage () and getimagetype (). The former returns the binary file byte array, and the latter returns the file type, the getimage () method has a parameter used to select the name of the file to be displayed or downloaded on the client. The files we show and downloaded here can not be in the virtual directory. The advantage of this method is that the files can be displayed and downloaded according to the permissions. We can see from the following method that, the actual file location is not in the virtual directory, so you can better control the permissions of the file, which is particularly useful for high security. This function can be implemented using stream objects in the previous ASP program. To facilitate testing, all the source code is listed and described and commented out in the source code.

First, create the getbinaryfile. asmx file:

We can. create a C # aspxwebcs project in. net, add a new project, select "Web service", and set the file name to getbinaryfile. asmx: Enter the following code in "view code": getbinaryfile. asmx. CS:

Using system; <br/> using system. collections; <br/> using system. componentmodel; <br/> using system. data; <br/> using system. diagnostics; <br/> using system. web; <br/> using system. web. ui; <br/> using system. web. services; <br/> using system. io; <br/> namespace xml.sz.luohuedu.net. aspxwebcs <br/>{< br/> /// <br/> <summary> /// abstract description of getbinaryfile. <Br/> // Web Services Name: getbinaryfile <br/> // function: return the binary byte array of a file object on the server. <Br/> // </Summary> <p> [WebService (namespace = "http://xml.sz.luohuedu.net/", <br/> description = "Exploitation in Web Services.. NET Framework. ")] <Br/> public class getbinaryfile: system. web. services. webService <br/>{< br/> # region component designer generated code <br/> // required by the Web Service designer <br/> private icontainer components = NULL; <br/> /// <br/> <summary> /// clear all resources in use. <Br/> // </Summary> <p> protected override void dispose (bool disposing) <br/>{< br/> If (disposing & amp; components! = NULL) <br/>{< br/> components. dispose (); <br/>}< br/> base. dispose (disposing); <br/>}< br/> # endregion <br/> public class images: system. web. services. webService <br/> {<br/> /// <br/> <summary> // method provided by the web service, returns the byte array of the given file. <Br/> // </Summary> <p> [webmethod (description = "method provided by the web service, returns the byte array of the given file")] <br/> Public byte [] getimage (string requestfilename) <br/> {<br/> // obtain an image of the server. <br/> /// If you test the image yourself, note: Modify the actual physical path <br/> If (requestfilename = NULL | requestfilename = "") <br/> return getbinaryfile ("D: \ picture. jpg "); <br/> else <br/> return getbinaryfile (" D: \ "+ requestfilename ); <br/>}< br/> /// <br/> <summary> /// getbinaryfile: The byte array of the file path. <Br/> // </Summary> <p> // </P> <p> // <returns> </returns> <br/> Public byte [] getbinaryfile (string filename) <br/>{< br/> If (file. exists (filename) <br/>{< br/> try <br/>{< br/> // open an existing file for reading. <Br/> filestream S = file. openread (filename); <br/> return convertstreamtobytebuffer (s); <br/>}< br/> catch (exception E) <br/>{< br/> return New byte [0]; <br/>}< br/> else <br/> {<br/> return New byte [0]; <br/>}< br/> // <br/> <summary> // convertstreamtobytebuffer: convert a given file to a binary byte array. <Br/> // </Summary> <p> // </P> <p> // <returns> </returns> <br/> Public byte [] convertstreamtobytebuffer (system. io. stream thestream) <br/>{< br/> int B1; <br/> system. io. memorystream tempstream = new system. io. memorystream (); <br/> while (b1 = thestream. readbyte ())! =-1) <br/>{< br/> tempstream. writebyte (byte) B1); <br/>}< br/> return tempstream. toarray (); <br/>}< br/> [webmethod (description = "method provided by the web service, return the given file type. ")] <Br/> Public String getimagetype () <br/> {<br/> // test only, you can perform dynamic output based on the actual file type <br/> return "image/jpg "; <br/>}< br/>

Once the above asmx file is created and compiled, We can compile the client code to call this web services.

First, "add web reference" and enter: http: // localhost/aspxwebcs/getbinaryfile. asmx. Next, we will write the intermediate file of the display file: getbinaryfileshow. aspx. Here, we only need to write the code in the subsequent code. The content of the getbinaryfileshow. aspx. CS file is as follows:

Using system; <br/> using system. collections; <br/> using system. componentmodel; <br/> using system. data; <br/> using system. drawing; <br/> using system. web; <br/> using system. web. sessionstate; <br/> using system. web. ui; <br/> using system. web. UI. webcontrols; <br/> using system. web. UI. htmlcontrols; <br/> using system. web. services; <br/> namespace aspxwebcs <br/>{< br/> /// <br/> <summary> /// getbinaryfileshow. <Br/> // </Summary> <p> public class getbinaryfileshow: system. web. UI. page <br/>{< br/> private void page_load (Object sender, system. eventargs e) <br/>{< br/> // place the user code here to initialize the page <br/> // define and initialize the file object; <br/> xml.sz.luohuedu.net. aspxwebcs. getbinaryfile. images oimage; <br/> oimage = new xml.sz.luohuedu.net. aspxwebcs. getbinaryfile. images (); <br/> // get the byte array of binary files; <br/> byte [] image = oimage. getimage (""); <br/> // /Convert to a stream that supports the storage area as the memory <br/> system. io. memorystream memstream = new system. io. memorystream (image); <br/> // defines and instantiates a bitmap object <br/> bitmap Bm = new Bitmap (memstream ); <br/> // output or download according to different conditions. <br/> response. clear (); <br/> // if the request string is specified for download, the file will be downloaded. <br/> // otherwise, the file will be displayed in the browser. <Br/> If (request. querystring ["Download"] = "1") <br/>{< br/> response. buffer = true; <br/> response. contenttype = "application/octet-stream"; <br/> // The download output file name OK .jpg is used as an example. You can dynamically decide based on the actual situation. <Br/> response. addheader ("content-disposition", "attachment?filename= OK .jpg"); <br/>}< br/> else <br/> response. contenttype = oimage. getimagetype (); <br/> response. binarywrite (image); <br/> response. end (); <br/>}< br/> # region web form designer generated code <br/> override protected void oninit (eventargs E) <br/>{< br/> // <br/> // codegen: Asp.. NET web form designer. <Br/> // <br/> initializecomponent (); <br/> base. oninit (E ); <br/>}< br/> /// <br/> <summary> // The method required by the designer. Do not use the code editor to modify the method. <br/> // /content of this method. <Br/> // </Summary> <p> private void initializecomponent () <br/>{< br/> This. load + = new system. eventhandler (this. page_load); <br/>}< br/> # endregion <br/>}< br/>

Finally, we will compile the final browsing page: getbinaryfile. aspx. This file is very simple and only needs the aspx file. The content is as follows:

<Meta name = "generator" content = "Microsoft Visual Studio 7.0"> <meta name = "code_language" content = "C #"> <meta name = "vs_defaultclientscript" content =" javaScript "> <meta name =" vs_targetschema "content =" http://schemas.microsoft.com/intellisense/ie5 ">

Ii. upload files through Web Services

There may be many ways to upload files to the server. In the method of using web services to upload files, the following method should be the simplest. As in the previous example, we first create the upload. asmx file. The content of upload. asmx. CS is as follows, which has been commented out:

Using system; <br/> using system. collections; <br/> using system. componentmodel; <br/> using system. data; <br/> using system. diagnostics; <br/> using system. web; <br/> using system. web. services; <br/> using system. io; <br/> namespace xml.sz.luohuedu.net. aspxwebcs <br/>{< br/> /// <br/> <summary> /// Summary of upload. <Br/> // </Summary> <p> [WebService (namespace = "http://xml.sz.luohuedu.net/", <br/> description = "Exploitation in Web Services.. NET Framework. ")] <Br/> public class upload: system. web. services. webService <br/> {<br/> Public upload () <br/> {<br/> // codegen: Asp. <br/> initializecomponent (); <br/>}< br/> # region component designer generated code <br/> // required by the Web Service designer <br/> private icontainer components = NULL; <br/> // <br/> <summary> // The designer supports the required methods. Do not use the code editor to modify the content of this method. <br/> //. <Br/> // </Summary> <p> private void initializecomponent () <br/>{< br/>}< br/> /// <br/> <summary> /// clear all resources in use. <Br/> // </Summary> <p> protected override void dispose (bool disposing) <br/>{< br/> If (disposing & amp; components! = NULL) <br/>{< br/> components. dispose (); <br/>}< br/> base. dispose (disposing); <br/>}< br/> # endregion <br/> [webmethod (description = "method provided by the web service, whether the file is uploaded successfully or not. ")] <Br/> Public String uploadfile (byte [] FS, string filename) <br/> {<br/> try <br/> {<br/> // define and instantiate a memory stream to store the submitted byte array. <Br/> memorystream M = new memorystream (FS); <br/> // defines the actual file object and saves the uploaded file. <Br/> filestream F = new filestream (server. mappath (". ") +" \ "<br/> + filename, filemode. create); <br/> // write data in the internal memory to a physical file <br/> M. writeto (f); <br/> M. close (); <br/> F. close (); <br/> F = NULL; <br/> M = NULL; <br/> return "the file has been uploaded successfully. "; <Br/>}< br/> catch (exception ex) <br/>{< br/> return ex. message; <br/>}< br/>

To upload a file, you must provide a form for you to select the file. Next we will create a page named upload. aspx to upload the file:

<Meta name = "generator" content = "Microsoft Visual Studio. net 7.0 "> <meta name =" code_language "content =" Visual Basic 7.0 "> <meta name =" vs_defaultclientscript "content =" JavaScript "> <meta name =" vs_targetschema "content = "http://schemas.microsoft.com/intellisense/ie5">

What we need to deal with is in the post code, which is described in detail below, upload. aspx. CS:

Using system; &lt;br/&gt; using system. collections; &lt;br/&gt; using system. componentmodel; &lt;br/&gt; using system. data; &lt;br/&gt; using system. drawing; &lt;br/&gt; using system. web; &lt;br/&gt; using system. web. sessionstate; &lt;br/&gt; using system. web. ui; &lt;br/&gt; using system. web. UI. webcontrols; &lt;br/&gt; using system. web. UI. htmlcontrols; &lt;br/&gt; using system. web. services; &lt;br/&gt; using system. io; &lt;br/&gt; namespace aspxwebcs &lt;br/&gt;{&lt; br/&gt; // &lt;br/&gt; &lt;summary&gt; /// Summary of upload. &lt;Br/&gt; // use this method to upload files through Web Services &lt;br/&gt; /// &lt;/Summary&gt; &lt;p&gt; public class upload: system. web. UI. page &lt;br/&gt; {&lt;br/&gt; protected system. web. UI. htmlcontrols. htmlinputfile myfile; &lt;br/&gt; protected system. web. UI. webcontrols. button button1; &lt;br/&gt; private void page_load (Object sender, system. eventargs E) &lt;br/&gt;{&lt; br/&gt; // place the user code here to initialize the page &lt;br/&gt;}&lt; br/&gt; # region web form designer generated code &lt;br/&gt; override protected void Oninit (eventargs e) &lt;br/&gt;{&lt; br/&gt; // &lt;br/&gt; // codegen: This call is required by the ASP. NET web forms designer. &lt;Br/&gt; // &lt;br/&gt; initializecomponent (); &lt;br/&gt; base. oninit (E ); &lt;br/&gt;}&lt; br/&gt; /// &lt;br/&gt; &lt;summary&gt; // The method required by the designer. Do not use the code editor to modify the method. &lt;br/&gt; // /content of this method. &lt;Br/&gt; // &lt;/Summary&gt; &lt;p&gt; private void initializecomponent () &lt;br/&gt;{&lt; br/&gt; This. button1.click + = new system. eventhandler (this. button#click); &lt;br/&gt; This. load + = new system. eventhandler (this. page_load); &lt;br/&gt;}&lt; br/&gt; # endregion &lt;br/&gt; private void button#click (Object sender, system. eventargs e) &lt;br/&gt;{&lt; br/&gt; // first obtain the uploaded file information and file stream &lt;br/&gt; If (myfile. postedfile! = NULL) &lt;br/&gt;{&lt; br/&gt; system. web. httpfilecollection ofiles; &lt;br/&gt; ofiles = system. web. httpcontext. current. request. files; &lt;br/&gt; If (ofiles. count &lt;/P&gt; &lt;p&gt; Finally, note that when saving the file, you must ensure that the complete path of the specified file (for example, "C: \ myfiles \ picture.jpg "), and make sure it is ASP. the account used by. NET provides the write permission for the directory to store files. When uploading a large file, you can use the maxrequestlength attribute of the <pttpruntime&gt; element to increase the maximum file size. For example: </pttpruntime&gt; &lt;/P&gt; &lt;p&gt; &lt;XMP&gt; &lt;configuration&gt; &lt;system. web&gt; <pttpruntime maxrequestlength = "1048576" executiontimeout = "3600"&gt; </pttpruntime&gt; &lt;/system. web&gt; &lt;/configuration&gt;

Maxrequestlength indicates the maximum number of bytes uploaded in http mode supported by ASP. NET. This restriction can be used to prevent DoS attacks caused by a large number of files being transferred to the server. The specified size is in KB. The default value is 4096 KB (4 MB ). Executiontimeout: indicates the maximum number of seconds allowed to execute a request before it is automatically disabled by ASP. NET. When the file size exceeds the specified size, if a DNS error occurs in the browser or the service is unavailable, modify the above configuration to increase the number of configurations.

When uploading a large file, you may receive the following error message:

Aspnet_wp.exe (PID: 1520) is recycled because the memory consumption exceeds 460 MB (60 percent of available RAM ). &lt;Br/&gt;

If this error message is returned, add

The value of the memorylimit attribute in the element. For example:

&lt;Configuration&gt; &lt;system. Web&gt; &lt;processmodel memorylimit = "80"&gt; &lt;/processmodel&gt; &lt;/system. Web&gt; &lt;/configuration&gt;

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.