Implement Web Services that support multipoint asynchronous upload of files in asp.net

Source: Internet
Author: User

The client application in this article does not include ASP. Net Web applications!

This document assumes that URL: http: // localhost/mywebservices/updownload. asmx

There are 4 program files in total (Web. Config will not be repeated)

Server Side:

The "Asynchronous" mentioned in the title has nothing special in the server-side program, but mainly through the client application
Implement Asynchronous call of related Web methods!

1. updownload. asmx, located in a Web shared directory of IIS, has the following code:

<% @ WebService Language = "c #" Codebehind = "UpDownLoad. asmx. cs" Class = "Service1" %>

2. updownload. asmx. cs, that is, the Codebehind of updownload. asmx, which is located in the bin subdirectory of a Web shared directory of IIS, the Code is as follows:

/*

This file is located in the bin subdirectory of the Web shared directory and compiled by executing the following command line:
Csc/t: library updownload. asmx. cs

*/
Using System. Diagnostics;
Using System. Web;
Using System. Web. Services;
Using System. IO;
Using System;

Public class Service1: System. Web. Services. WebService
{
[WebMethod]
Public string HelloWorld ()
{
Return "Hello World ";
}

// From the Web Method itself, it cannot be seen whether "synchronous" or "Asynchronous"
[WebMethod (Description = "to support multipart asynchronous file upload, this method must be called by the client in advance to generate a reserved space for Blank files with the specified FileName and Length on the server side! We recommend that the client synchronously call ")]
Public string CreateBlankFile (string FileName, int Length) // It is recommended that the client synchronously call
{
FileStream fs = new FileStream (Server. MapPath (".") + "\" + FileName, FileMode. OpenOrCreate, FileAccess. ReadWrite, FileShare. None );
Fs. Write (new byte [Length], 0, Length );
Fs. Close ();
Fs = null;
Return FileName + "(" + Length + ") the blank file has been created! ";
}

[WebMethod (Description = "provides a method for completely uploading the entire file at a time! We recommend that the client synchronously call ")]
Public string UploadFileBytes (byte [] Bytes, string FileName)
{
Return UploadFileChunkBytes (Bytes, 0, FileName );
}

[WebMethod (Description = "provides a FileName file block that is used only to upload data starting from Position at a time. The Bytes are stored in the corresponding byte location of the corresponding file on the server! Client asynchronous call is recommended ")]
// Here, you only need to provide one more Position parameter, and the rest will be called by the client asynchronously to achieve this goal easily!
Public string UploadFileChunkBytes (byte [] Bytes, int Position, string FileName)
{
Try
{
FileStream fs = new FileStream (Server. MapPath (".") + "\" + FileName, FileMode. OpenOrCreate, FileAccess. ReadWrite, FileShare. ReadWrite );
// The Bytes byte is written to the byte starting from Position of the corresponding file on the server.
Fs. Position = Position;
Fs. Write (Bytes, 0, Bytes. Length );
Fs. Close ();
Fs = null;
Return FileName + "file block: Location [" + Position + "," + (Position + Bytes. Length) + "] size (" + Bytes. Length + ") uploaded successfully! ";
}
Catch (Exception e)
{
Return e. Message;
}
}

[WebMethod]
Public byte [] DownloadFileBytes (string FileName)
{
If (File. Exists (FileName ))
{
Try
{
FileStream fs = File. OpenRead (FileName );
Int I = (int) fs. Length;
Byte [] ba = new byte [I];
Fs. Read (ba, 0, I );
Fs. Close ();
Return ba;
}
Catch
{
Return new byte [0];
}
}
Else
{
Return new byte [0];
}
}
}

// ================================================ ======================================

Client Side:
3. UpDownloadProxy. cs:
This file is generated by the following command:
% \ SDK \ v1.1 \ Bin \ wsdl.exe under the installation directory of Visual Studio. Net 2003
The command line is as follows:
Wsdl.exe/l: CS/out: UpDownloadProxy. cs http: // localhost/MyWebServices/updownload. asmx? Wsdl
The generated local client proxy code has generated asynchronous and synchronous execution methods for each Web Method, for example:
Public string HelloWorld (){}
Public System. IAsyncResult BeginHelloWorld (...){}
Public string EndHelloWorld (...){}

The following is the complete UpDownloadProxy. cs code generated by the command line, which will not be modified:
/*

Run the following command to compile and generate UpDownloadProxy. dll:
Csc/t: library UpDownloadProxy. cs

*/

//------------------------------------------------------------------------------
// <Autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// The code is regenerated.
/// </Autogenerated>
//------------------------------------------------------------------------------

//
// The source code is automatically generated by wsdl, Version = 1.1.4322.573.
//
Using System. Diagnostics;
Using System. Xml. Serialization;
Using System;
Using System. Web. Services. Protocols;
Using System. ComponentModel;
Using System. Web. Services;

/// <Remarks/>
[System. Diagnostics. DebuggerStepThroughAttribute ()]
[System. ComponentModel. DesignerCategoryAttribute ("code")]
[System. Web. Services. WebServiceBindingAttribute (Name = "Service1Soap", Namespace = "http://tempuri.org/")]
Public class Service1: System. Web. Services. Protocols. SoapHttpClientProtocol {

/// <Remarks/>
Public Service1 (){
This. Url = "http: // localhost/MyWebServices/updownload. asmx ";
}

/// <Remarks/>
[System. web. services. protocols. soapdocumentmethodattrispace ("http://tempuri.org/HelloWorld", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System. web. services. description. soapBindingUse. literal, ParameterStyle = System. web. services. protocols. soapParameterStyle. wrapped)]
Public string HelloWorld (){
Object [] results = this. Invoke ("HelloWorld", new object [0]);
Return (string) (results [0]);
}

/// <Remarks/>
Public System. IAsyncResult BeginHelloWorld (System. AsyncCallback callback, object asyncState ){
Return this. BeginInvoke ("HelloWorld", new object [0], callback, asyncState );
}

/// <Remarks/>
Public string EndHelloWorld (System. IAsyncResult asyncResult ){
Object [] results = this. EndInvoke (asyncResult );
Return (string) (results [0]);
}

/// <Remarks/>
[System. web. services. protocols. soapdocumentmethodattrispace ("http://tempuri.org/CreateBlankFile", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System. web. services. description. soapBindingUse. literal, ParameterStyle = System. web. services. protocols. soapParameterStyle. wrapped)]
Public string CreateBlankFile (string FileName, int Length ){
Object [] results = this. Invoke ("CreateBlankFile", new object [] {
FileName,
Length });
Return (string) (results [0]);
}

/// <Remarks/>
Public System. IAsyncResult BeginCreateBlankFile (string FileName, int Length, System. AsyncCallback callback, object asyncState ){
Return this. BeginInvoke ("CreateBlankFile", new object [] {
FileName,
Length}, callback, asyncState );
}

/// <Remarks/>
Public string EndCreateBlankFile (System. IAsyncResult asyncResult ){
Object [] results = this. EndInvoke (asyncResult );
Return (string) (results [0]);
}

/// <Remarks/>
[System. web. services. protocols. soapdocumentmethodattrispace ("http://tempuri.org/UploadFileBytes", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System. web. services. description. soapBindingUse. literal, ParameterStyle = System. web. services. protocols. soapParameterStyle. wrapped)]
Public string UploadFileBytes ([System. Xml. Serialization. XmlElementAttribute (DataType = "base64Binary")] System. Byte [] Bytes, string FileName ){
Object [] results = this. Invoke ("UploadFileBytes", new object [] {
Bytes,
FileName });
Return (string) (results [0]);
}

/// <Remarks/>
Public System. IAsyncResult BeginUploadFileBytes (System. Byte [] Bytes, string FileName, System. AsyncCallback callback, object asyncState ){
Return this. BeginInvoke ("UploadFileBytes", new object [] {
Bytes,
FileName}, callback, asyncState );
}

/// <Remarks/>
Public string EndUploadFileBytes (System. IAsyncResult asyncResult ){
Object [] results = this. EndInvoke (asyncResult );
Return (string) (results [0]);
}

/// <Remarks/>
[System. web. services. protocols. soapdocumentmethodattrispace ("http://tempuri.org/UploadFileChunkBytes", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System. web. services. description. soapBindingUse. literal, ParameterStyle = System. web. services. protocols. soapParameterStyle. wrapped)]
Public string UploadFileChunkBytes ([System. Xml. Serialization. XmlElementAttribute (ype = "base64Binary")] System. Byte [] Bytes, int Position, string FileName ){
Object [] results = this. Invoke ("UploadFileChunkBytes", new object [] {
Bytes,
Position,
FileName });
Return (string) (results [0]);
}

/// <Remarks/>
Public System. IAsyncResult BeginUploadFileChunkBytes (System. Byte [] Bytes, int Position, string FileName, System. AsyncCallback callback, object asyncState ){
Return this. BeginInvoke ("UploadFileChunkBytes", new object [] {
Bytes,
Position,
FileName}, callback, asyncState );
}

/// <Remarks/>
Public string EndUploadFileChunkBytes (System. IAsyncResult asyncResult ){
Object [] results = this. EndInvoke (asyncResult );
Return (string) (results [0]);
}

/// <Remarks/>
[System. web. services. protocols. soapdocumentmethodattrispace ("http://tempuri.org/DownloadFileBytes", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System. web. services. description. soapBindingUse. literal, ParameterStyle = System. web. services. protocols. soapParameterStyle. wrapped)]
[Return: System. Xml. Serialization. XmlElementAttribute (DataType = "base64Binary")]
Public System. Byte [] DownloadFileBytes (string FileName ){
Object [] results = this. Invoke ("DownloadFileBytes", new object [] {
FileName });
Return (System. Byte []) (results [0]);
}

/// <Remarks/>
Public System. IAsyncResult BeginDownloadFileBytes (string FileName, System. AsyncCallback callback, object asyncState ){
Return this. BeginInvoke ("DownloadFileBytes", new object [] {
FileName}, callback, asyncState );
}

/// <Remarks/>
Public System. Byte [] EndDownloadFileBytes (System. IAsyncResult asyncResult ){
Object [] results = this. EndInvoke (asyncResult );
Return (System. Byte []) (results [0]);
}
}

// ================================================ ======================================
4. UpDownloadClient. cs:
This program is the core code for implementing multipart asynchronous upload of files:

/*

Compile by executing the following command line:
Csc updownloadClient. cs/r: updownloadproxy. dll

*/
Using System;
Using System. IO;

Public class Class1
{
Static void Main (string [] args)
{
// Download (ServerSidepath, ClientSidePath)
Download (@ "e: \ test.jpg", @ "f: \ test_local.jpg ");
System. Console. WriteLine ("down End ");

System. Console. WriteLine ("Synchronize up file exec ...");
UploadFile (@ "e: \ Northwind. mdb ");
System. Console. WriteLine ("Synchronize up file End \ n ");

System. Console. WriteLine ("Asynchronous up chunks exec ...");
UploadFileChunks (@ "e: \ test.rar", 64 );
System. Console. ReadLine ();
}

Public static void UploadFile (string LocalFileName)
{
Service1 xx = new Service1 ();
FileStream fs = new FileStream (LocalFileName, FileMode. Open); // Client Side Path
Byte [] buffer = new byte [fs. Length];
Fs. Read (buffer, 0, buffer. Length );
// Call the local Web Sevices proxy Method of "synchronous execution", which is equivalent to synchronously calling the Web Method!
Xx. UploadFileBytes (buffer, System. IO. Path. GetFileName (LocalFileName ));
}

// Specify the path of the local file to be uploaded and the size of each file block to be uploaded
Public static void UploadFileChunks (string LocalFileName, int ChunkSize)
{
Service1 xx = new Service1 ();
String filename = System. IO. Path. GetFileName (LocalFileName );

FileStream fs = new FileStream (LocalFileName, FileMode. Open); // Client Side Path
// Fs = File. OpenRead (LocalFileName );

Int r = (int) fs. Length; // records the number of bytes that have not been uploaded. The initial value is the file size.

// Call the local Web Sevices proxy Method of "synchronous execution", which is equivalent to synchronously calling the Web Method!
// Reserve server space
Xx. CreateBlankFile (filename, r );
Int size = ChunkSize * 1024;
Int k = 0; // records the number of uploaded bytes.
I ++; // used to record the number of uploaded files
While (r> = size)
{
Byte [] buffer = new byte [size];
Fs. Read (buffer, 0, buffer. Length );
// Call the Method of the Local Web Sevices proxy class of "Asynchronous execution", which is equivalent to asynchronously calling the Web Method!
// The buffer byte is written to the byte starting from Position = k of the corresponding file on the server.
Xx. BeginUploadFileChunkBytes (buffer, k, filename, new AsyncCallback (UploadFileChunkCallback), xx );
K + = size;
R-= size;
I ++;
}
If (r> 0) // The remaining zero Header
{
Byte [] buffer = new byte [r];
Fs. Read (buffer, 0, buffer. Length );
// Call the Method of the Local Web Sevices proxy class of "Asynchronous execution", which is equivalent to asynchronously calling the Web Method!
// The buffer byte is written to the byte starting from Position = k of the corresponding file on the server.
Xx. BeginUploadFileChunkBytes (buffer, k, filename, new AsyncCallback (UploadFileChunkCallback), xx );
I ++;
}
Fs. Close ();

}

Private static int I =-1; // records the number of uploaded files

Private static void UploadFileChunkCallback (IAsyncResult ar)
{
Service1 x = (Service1) ar. AsyncState;
Console. WriteLine (x. EndUploadFileChunkBytes (ar ));
If (-- I = 0)
{
Console. WriteLine ("Asynchronous up all chunks end ");
}
}

Public static void Download (string ServerSideFileName, string LocalFileName)
{
Service1 xx = new Service1 ();
Byte [] ba = xx. DownloadFileBytes (ServerSideFileName); // Server Side Path

FileStream fs = new FileStream (LocalFileName, FileMode. Create); // Client Side Path
Fs. Write (ba, 0, ba. Length );
Fs. Close ();
}
}

// ================================================ ============================================
At this point, we have completed the task by hand. The reason why VS is not used is to make the code concise and clear!
Microshaoft. Night is so approachable! (PMPMP to MS)
Uploading files through Web Sevices is very simple, and even easier than traditional http Web upload!
At the same time, it is easier to implement multipart asynchronous upload of files:
Server code is not special!
The Client code is a little more complex!

Related Article

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.