Upload and download files through Web Services _ [wonderful world of Meng xianhui]

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;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. Web;
Using system. Web. UI;
Using system. Web. Services;
Using system. IO;

Namespace xml.sz.luohuedu.net. aspxwebcs
{
///

/// Summary of getbinaryfile.
/// Web Services Name: getbinaryfile
/// Function: return the binary byte array of a file object on the server.
///

[WebService (namespace = "http://xml.sz.luohuedu.net /",
Description = "Use the. NET Framework in web services to transmit binary files. ")]
Public class getbinaryfile: system. Web. Services. WebService
{

# Region component designer generated code
// Required by the Web Service designer
Private icontainer components = NULL;

///

/// Clear all resources in use.
///

Protected override void dispose (bool disposing)
{
If (disposing & components! = NULL)
{
Components. Dispose ();
}
Base. Dispose (disposing );
}

# Endregion

Public class images: system. Web. Services. WebService
{
///

/// The method provided by the web service, returns the byte array of the given file.
///

[Webmethod (description = "the method provided by the web service, returns the byte array of the given file")]
Public byte [] getimage (string requestfilename)
{
/// Get an image of the server
/// If you test it by yourself, make sure to modify the actual physical path below
If (requestfilename = NULL | requestfilename = "")
Return getbinaryfile ("D: // picture. jpg ");
Else
Return getbinaryfile ("D: //" + requestfilename );
}

///

/// Getbinaryfile: returns the byte array of the given file path.
///

//////
Public byte [] getbinaryfile (string filename)
{
If (file. exists (filename ))
{
Try
{
/// Open an existing file for reading.
Filestream S = file. openread (filename );
Return convertstreamtobytebuffer (s );
}
Catch (exception E)
{
Return new byte [0];
}
}
Else
{
Return new byte [0];
}
}
///

/// Convertstreamtobytebuffer: convert a given file flow into a binary byte array.
///

//////
Public byte [] convertstreamtobytebuffer (system. Io. Stream thestream)
{
Int B1;
System. Io. memorystream tempstream = new system. Io. memorystream ();
While (b1 = thestream. readbyte ())! =-1)
{
Tempstream. writebyte (byte) B1 ));
}
Return tempstream. toarray ();
}
[Webmethod (description = "method provided by the web service, returns the given file type. ")]
Public String getimagetype ()
{
/// This is only a test. You can perform dynamic output based on the actual file type.
Return "image/jpg ";
}
}
}
}
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;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. Web;
Using system. Web. sessionstate;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. htmlcontrols;
Using system. Web. Services;

Namespace aspxwebcs
{
///

/// Summary of getbinaryfileshow.
///

Public class getbinaryfileshow: system. Web. UI. Page
{

Private void page_load (Object sender, system. eventargs E)
{
// Place user code here to initialize the page
/// Define and initialize the object;
Xml.sz.luohuedu.net. aspxwebcs. getbinaryfile. Images oimage;
Oimage = new xml.sz.luohuedu.net. aspxwebcs. getbinaryfile. Images ();
/// Obtain the byte array of the binary file;
Byte [] image = oimage. getimage ("");
/// Convert to a stream that supports the storage zone as the memory
System. Io. memorystream memstream = new system. Io. memorystream (image );
/// Define and instantiate a bitmap object
Bitmap Bm = new Bitmap (memstream );
/// Output or download according to different conditions;
Response. Clear ();
/// If the request string is specified for download, the object will be downloaded;
/// Otherwise, it will be displayed in the browser.
If (request. querystring ["Download"] = "1 ")
{
Response. Buffer = true;
Response. contenttype = "application/octet-stream ";
/// The Name Of The downloaded output file OK .jpg is used as an example. You can decide it dynamically based on the actual situation.
Response. addheader ("content-disposition", "attachment?filename= OK .jpg ");
}
Else
Response. contenttype = oimage. getimagetype ();
Response. binarywrite (image );
Response. End ();
}

# Region web form designer generated code
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

///

/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///

Private void initializecomponent ()
{
This. Load + = new system. eventhandler (this. page_load );

}
# Endregion
}
}
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:
Inherits = "aspxwebcs. getbinaryfile" %>




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;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. Web;
Using system. Web. Services;
Using system. IO;

Namespace xml.sz.luohuedu.net. aspxwebcs
{
///

/// Summary of upload.
///

[WebService (namespace = "http://xml.sz.luohuedu.net /",
Description = "Use the. NET Framework in web services to upload files. ")]
Public class upload: system. Web. Services. WebService
{
Public upload ()
{
// Codegen: This call is required by the ASP. NET web service designer.
Initializecomponent ();
}

# Region component designer generated code

// Required by the Web Service designer
Private icontainer components = NULL;

///

/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///

Private void initializecomponent ()
{
}

///

/// Clear all resources in use.
///

Protected override void dispose (bool disposing)
{
If (disposing & components! = NULL)
{
Components. Dispose ();
}
Base. Dispose (disposing );
}

# Endregion

[Webmethod (description = "method provided by the web service, returns whether the file is uploaded successfully or not. ")]
Public String uploadfile (byte [] FS, string filename)
{
Try
{
/// Define and instantiate a memory stream to store the submitted byte array.
Memorystream M = new memorystream (FS );
/// Define the actual object and save the uploaded object.
Filestream F = new filestream (server. mappath (".") + "//"
+ Filename, filemode. Create );
/// Write data in the memory to a physical file
M. writeto (f );
M. Close ();
F. Close ();
F = NULL;
M = NULL;
Return "the file has been uploaded successfully. ";
}
Catch (exception ex)
{
Return ex. message;
}
}
}
}
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:
Inherits = "aspxwebcs. Upload" %>




What we need to deal with is in the post code, which is described in detail below, upload. aspx. CS:
Using system;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. Web;
Using system. Web. sessionstate;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. htmlcontrols;
Using system. Web. Services;
Using system. IO;

Namespace aspxwebcs
{
///

/// Summary of upload.
/// Use this method to upload files through Web Services
///

Public class upload: system. Web. UI. Page
{
Protected system. Web. UI. htmlcontrols. htmlinputfile myfile;
Protected system. Web. UI. webcontrols. Button button1;

Private void page_load (Object sender, system. eventargs E)
{
// Place user code here to initialize the page
}

# Region web form designer generated code
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

///

/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///

Private void initializecomponent ()
{
This. button1.click + = new system. eventhandler (this. button#click );
This. Load + = new system. eventhandler (this. page_load );

}
# Endregion

Private void button#click (Object sender, system. eventargs E)
{
/// First obtain the uploaded file information and file stream
If (myfile. postedfile! = NULL)
{
System. Web. httpfilecollection ofiles;
Ofiles = system. Web. httpcontext. Current. Request. files;
If (ofiles. Count {
Response. Write ("select a file. ");
Response. End ();
}

String filepath = ofiles [0]. filename;
If (filepath = "" | filepath = NULL)
{
Response. Write ("select a file. ");
Response. End ();
}
String filename = filepath. substring (filepath. lastindexof ("//") + 1 );
Try
{
/// Process the uploaded file stream information.
Byte [] B = new byte [ofiles [0]. contentlength];
System. Io. Stream FS;
Xml.sz.luohuedu.net. aspxwebcs. Upload O;
O = new xml.sz.luohuedu.net. aspxwebcs. Upload ();
FS = (system. Io. Stream) ofiles [0]. inputstream;
FS. Read (B, 0, ofiles [0]. contentlength );
/// Call the uploadfile method of web services to upload files.
Response. Write (O. uploadfile (B, filename ));
FS. Close ();
}
Catch (exception ex)
{
Response. Write (ex. Message );
}
}
Else
{
Response. Write ("select a file ");
}
}
}
}
Finally, make sure that the complete path of the specified file (for example, "C:/myfiles/picture.jpg") and 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 element to increase the maximum file size. For example:




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 ).
If this error message is returned, add the value of the memorylimit attribute in the element of the web. config file of the application. For example:



I can test it on my machine and upload files of 50 MB or more. The above code is tested and passed in Windows XP +. NET 1.0 + vs. net2002.
.

This article is transferred from
Http://dotnet.aspx.cc/article/6381bd5f-51f3-4339-4239-1328564a1b2a/read.aspx

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.