How to upload file data using WebClient. UploadData

Source: Internet
Author: User

Suppose a website has a form, for example (url: http: // localhost/login. aspx ):
Account
Password

We need to submit data to this form in the program. For this form, we can use the WebClient. UploadData method to splice the data to be uploaded into characters. The program is very simple:

String uriString = "http: // localhost/login. aspx ";
// Create a new WebClient instance.
WebClient myWebClient = new WebClient ();
String postData = "Username = admin & Password = admin ";
// Note the ContentType of the string.
MyWebClient. Headers. Add ("Content-Type", "application/x-www-form-urlencoded ");
// Convert to a binary array
Byte [] byteArray = Encoding. ASCII. GetBytes (postData );
// Upload data and obtain the returned binary data.
Byte [] responseArray = myWebClient. UploadData (uriString, "POST", byteArray );


For file upload forms, for example (url: http: // localhost/uploadFile. aspx ):
File

For this form, we can use
String uriString = "http: // localhost/uploadFile. aspx ";

// Create a new WebClient instance.
WebClient myWebClient = new WebClient ();

String fileName = @ "C: upload.txt ";

// Directly upload and obtain the returned binary data.
Byte [] responseArray = myWebClient. UploadFile (uriString, "POST", fileName );


There is also a form that contains not only text but also files, such as (url: http: // localhost/uploadData. aspx ):
File Name
File

For this form, it seems that the previous two methods are not applicable. For the first method, strings cannot be directly spelled. For the second method, we can only upload files and return to the first method, note:
Public byte [] UploadData (
String address,
String method,
Byte [] data
);
In the first example, the value of the byte [] data parameter is obtained by concatenating strings. This is obviously not applicable to such forms. In turn, for uploadData. for a program such as aspx, what is the stream obtained in the background by submitting data directly through the webpage? (In my previous blog, I analyzed this problem: asp no-component upload progress bar solution). The final data is as follows:

----------------------------- 7d429871607fe
Content-Disposition: form-data; name = "file1"; filename = "G: homepage.txt"
Content-Type: text/plain
Baoyu: http://www.webuc.net
----------------------------- 7d429871607fe
Content-Disposition: form-data; name = "filename"
Default filename
----------------------------- 7d429871607fe --


Therefore, you only need to combine such a byte [] data Post to achieve the same effect. However, you must note that the ContentType of a file to be uploaded is different. For example, the ContentType is "multipart/form-data; boundary = ------------------------- 7d429871607fe ". With ContentType, we can know boundary (that is, the above "--------------------------- 7d429871607fe"). After knowing boundary, we can construct the byte [] data we need. Finally, do not forget to upload the constructed ContentType to WebClient (for example, webClient. headers. add ("Content-Type", ContentType);) in this way, you can use WebClient. the UploadData method uploads the file data.

The Code is as follows:
Generate binary data encapsulation

Using System;
Using System. Web;
Using System. IO;
Using System. Net;
Using System. Text;
Using System. Collections;

Namespace UploadData. Common
...{
/** // <Summary>
/// Create the binary array required by the WebClient. UploadData Method
/// </Summary>
Public class CreateBytes
...{
Encoding encoding = Encoding. UTF8;

/** // <Summary>
/// Concatenate all binary arrays into an array
/// </Summary>
/// <Param name = "byteArrays"> array </param>
/// <Returns> </returns>
/// <Remarks> Add the end boundary </remarks>
Public byte [] JoinBytes (ArrayList byteArrays)
...{
Int length = 0;
Int readLength = 0;

// Add the end Boundary
String endBoundary = Boundary + "-- rn"; // end the Boundary.
Byte [] endBoundaryBytes = encoding. GetBytes (endBoundary );
ByteArrays. Add (endBoundaryBytes );

Foreach (byte [] B in byteArrays)
...{
Length + = B. Length;
}
Byte [] bytes = new byte [length];

// Traverse and copy
//
Foreach (byte [] B in byteArrays)
...{
B. CopyTo (bytes, readLength );
ReadLength + = B. Length;
}

Return bytes;
}

Public bool UploadData (string uploadUrl, byte [] bytes, out byte [] responseBytes)
...{
WebClient webClient = new WebClient ();
WebClient. Headers. Add ("Content-Type", ContentType );

Try
...{
ResponseBytes = webClient. UploadData (uploadUrl, bytes );
Return true;
}
Catch (WebException ex)
...{
Stream resp = ex. Response. GetResponseStream ();
ResponseBytes = new byte [ex. Response. ContentLength];
Resp. Read (responseBytes, 0, responseBytes. Length );
}
Return false;
}



/** // <Summary>
/// Obtain the binary array of the common form Area
/// </Summary>
/// <Param name = "fieldName"> form name </param>
/// <Param name = "fieldValue"> form value </param>
/// <Returns> </returns>
/// <Remarks>
// --------------------------------- 7d52ee27210a3crnContent-Disposition: form-data; name = "form name" rnrn form value rn
/// </Remarks>
Public byte [] CreateFieldData (string fieldName, string fieldValue)
...{
String textTemplate = Boundary + "rnContent-Disposition: form-data; name =" {0} "rnrn {1} rn ";
String text = String. Format (textTemplate, fieldName, fieldValue );
Byte [] bytes = encoding. GetBytes (text );
Return bytes;
}


/** // <Summary>
/// Obtain the binary array of the file upload form Area
/// </Summary>
/// <Param name = "fieldName"> form name </param>
/// <Param name = "filename"> file name </param>
/// <Param name = "contentType"> file type </param>
/// <Param name = "contentLength"> file length </param>
/// <Param name = "stream"> file stream </param>
/// <Returns> binary array </returns>
Public byte [] CreateFieldData (string fieldName, string filename, string contentType, byte [] fileBytes)
...{
String end = "rn ";
String textTemplate = Boundary + "rnContent-Disposition: form-data; name =" {0} "; filename =" {1} "rnContent-Type: {2} rnrn ";

// Header data
String data = String. Format (textTemplate, fieldName, filename, contentType );
Byte [] bytes = encoding. GetBytes (data );



// End data
Byte [] endBytes = encoding. GetBytes (end );

// The merged array
Byte [] fieldData = new byte [bytes. Length + fileBytes. Length + endBytes. Length];

Bytes. CopyTo (fieldData, 0); // header data
FileBytes. CopyTo (fieldData, bytes. Length); // binary data of the file
EndBytes. CopyTo (fieldData, bytes. Length + fileBytes. Length); // rn

Return fieldData;
}


Attribute # region attribute
Public string Boundary
...{
Get
...{
String [] bArray, ctArray;
String contentType = ContentType;
CtArray = contentType. Split (';');
If (ctArray [0]. Trim (). ToLower () = "multipart/form-data ")
...{
BArray = ctArray [1]. Split ('= ');
Return "--" + bArray [1];
}
Return null;
}
}

Public string ContentType
...{
Get ...{
If (HttpContext. Current = null)
...{
Return "multipart/form-data; boundary = --------------------------- 7d5b915500cee ";
}
Return HttpContext. Current. Request. ContentType;
}
}
# Endregion
}
}


Call in Winform


Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;

Using UploadData. Common;
Using System. IO;

Namespace UploadDataWin
...{
/** // <Summary>
/// Summary of frmUpload.
/// </Summary>
Public class frmUpload: System. Windows. Forms. Form
...{
Private System. Windows. Forms. Label lblAmigoToken;
Private System. Windows. Forms. TextBox txtAmigoToken;
Private System. Windows. Forms. Label lblFilename;
Private System. Windows. Forms. TextBox txtFilename;
Private System. Windows. Forms. Button btnBrowse;
Private System. Windows. Forms. TextBox txtFileData;
Private System. Windows. Forms. Label lblFileData;
Private System. Windows. Forms. Button btnUpload;
Private System. Windows. Forms. OpenFileDialog openFileDialog1;
Private System. Windows. Forms. TextBox txtResponse;
/** // <Summary>
/// Required designer variables.
/// </Summary>
Private System. ComponentModel. Container components = null;

Public frmUpload ()
...{
//
// Required for Windows Form Designer support
//
InitializeComponent ();

//
// TODO: add Any constructor code after InitializeComponent calls
//
}

/** // <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void Dispose (bool disposing)
...{
If (disposing)
...{
If (components! = Null)
...{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

Code generated by Windows Form Designer # code generated by region Windows Form Designer
/** // <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void InitializeComponent ()
...{
This. lblAmigoToken = new System. Windows. Forms. Label ();
This.txt AmigoToken = new System. Windows. Forms. TextBox ();
This. lblFilename = new System. Windows. Forms. Label ();
This.txt Filename = new System. Windows. Forms. TextBox ();
This. btnBrowse = new System. Windows. Forms. Button ();
This.txt FileData = new System. Windows. Forms. TextBox ();
This. lblFileData = new System. Windows. Forms. Label ();
This. btnUpload = new System. Windows. Forms. Button ();
This. openFileDialog1 = new System. Windows. Forms. OpenFileDialog ();
This.txt Response = new System. Windows. Forms. TextBox ();
This. SuspendLayout ();
//
// LblAmigoToken
//
This. lblAmigoToken. Location = new System. Drawing. Point (40, 48 );
This. lblAmigoToken. Name = "lblAmigoToken ";
This. lblAmigoToken. Size = new System. Drawing. Size (72, 23 );
This. lblAmigoToken. TabIndex = 0;
This. lblAmigoToken. Text = "AmigoToken ";
//
// TxtAmigoToken
//
This.txt AmigoToken. Location = new System. Drawing. Point (120, 48 );
This.txt AmigoToken. Name = "txtAmigoToken ";
This.txt AmigoToken. Size = new System. Drawing. Size (248, 21 );
This.txt AmigoToken. TabIndex = 1;
This.txt AmigoToken. Text = "";
//
// LblFilename
//
This. lblFilename. Location = new System. Drawing. Point (40, 96 );
This. lblFilename. Name = "lblFilename ";
This. lblFilename. Size = new System. Drawing. Size (80, 23 );
This. lblFilename. TabIndex = 2;
This. lblFilename. Text = "Filename ";
//
// TxtFilename
//
This.txt Filename. Location = new System. Drawing. Point (120, 96 );
This.txt Filename. Name = "txtFilename ";
This.txt Filename. Size = new System. Drawing. Size (248, 21 );
This.txt Filename. TabIndex = 3;
This.txt Filename. Text = "";
//
// BtnBrowse
//
This. btnBrowse. Location = new System. Drawing. Point (296,144 );
This. btnBrowse. Name = "btnBrowse ";
This. btnBrowse. TabIndex = 4;
This. btnBrowse. Text = "Browse ...";
This. btnBrowse. Click + = new System. EventHandler (this. btnBrowse_Click );
//
// TxtFileData
//
This.txt FileData. Location = new System. Drawing. Point (120,144 );
This.txt FileData. Name = "txtFileData ";
This.txt FileData. Size = new System. Drawing. Size (168, 21 );
This.txt FileData. TabIndex = 5;
This.txt FileData. Text = "";
//
// LblFileData
//
This. lblFileData. Location = new System. Drawing. Point (40,144 );
This. lblFileData. Name = "lblFileData ";
This. lblFileData. Size = new System. Drawing. Size (72, 23 );
This. lblFileData. TabIndex = 6;
This. lblFileData. Text = "FileData ";
//
// BtnUpload
//
This. btnUpload. Location = new System. Drawing. Point (48,184 );
This. btnUpload. Name = "btnUpload ";
This. btnUpload. TabIndex = 7;
This. btnUpload. Text = "Upload ";
This. btnUpload. Click + = new System. EventHandler (this. btnUpload_Click );
//
// TxtResponse
//
This.txt Response. Location = new System. Drawing. Point (136,184 );
This.txt Response. Multiline = true;
This.txt Response. Name = "txtResponse ";
This.txt Response. Size = new System. Drawing. Size (248, 72 );
This.txt Response. TabIndex = 8;
This.txt Response. Text = "";
//
// FrmUpload
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (400,269 );
This.Controls.Add(this.txt Response );
This. Controls. Add (this. btnUpload );
This. Controls. Add (this. lblFileData );
This.Controls.Add(this.txt FileData );
This. Controls. Add (this. btnBrowse );
This.Controls.Add(this.txt Filename );
This. Controls. Add (this. lblFilename );
This.Controls.Add(this.txt AmigoToken );
This. Controls. Add (this. lblAmigoToken );
This. Name = "frmUpload ";
This. Text = "frmUpload ";
This. ResumeLayout (false );

}
# Endregion

/** // <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main ()
...{
Application. Run (new frmUpload ());
}

Private void btnUpload_Click (object sender, System. EventArgs e)
...{
// Non-empty check
If (txtAmigoToken. Text. Trim () = "" | txtFilename. Text = "" | txtFileData. Text. Trim () = "")
...{
MessageBox. Show ("Please fill data ");
Return;
}

// File path to be uploaded
String path = txtFileData. Text. Trim ();

// Check whether the file exists
If (! File. Exists (path ))
...{
MessageBox. Show ("{0} does not exist! ", Path );
Return;
}

// Read the file stream
FileStream fs = new FileStream (path, FileMode. Open,
FileAccess. Read, FileShare. Read );

// This part needs to be improved
String ContentType = "application/octet-stream ";
Byte [] fileBytes = new byte [fs. Length];
Fs. Read (fileBytes, 0, Convert. ToInt32 (fs. Length ));


// Generate the binary array to be uploaded
CreateBytes cb = new CreateBytes ();
// All form data
ArrayList bytesArray = new ArrayList ();
// Normal Form
BytesArray. Add (cb. CreateFieldData ("FileName", txtFilename. Text ));
BytesArray. Add (cb. CreateFieldData ("AmigoToken", txtAmigoToken. Text ));
// File form
BytesArray. Add (cb. CreateFieldData ("FileData", path
, ContentType, fileBytes ));

// Merge all forms and generate a binary array
Byte [] bytes = cb. JoinBytes (bytesArray );

// Returned content
Byte [] responseBytes;

// Upload to the specified Url
Bool uploaded = cb. UploadData ("http: // localhost/UploadData/UploadAvatar. aspx", bytes, out responseBytes );

// Output the returned content to the file
Using (FileStream file = new FileStream (@ "c: response. text", FileMode. Create, FileAccess. Write, FileShare. Read ))
...{
File. Write (responseBytes, 0, responseBytes. Length );
}

TxtResponse. Text = System. Text. Encoding. UTF8.GetString (responseBytes );

}

Private void btnBrowse_Click (object sender, System. EventArgs e)
...{
If (openFileDialog1.ShowDialog () = DialogResult. OK)
...{
TxtFileData. Text = openFileDialog1.FileName;
}

}
}
}


Complete code see Attachment: UploadData.rar (38 K) (http://bbs.openlab.net.cn/PostAttachment.aspx? PostID = 400927), decompress the package, and create a virtual directory "UploadData" for the web directory, where UploadAvatar. aspx is the actual upload processing page. If the upload is successful, information such as the file name and file type will be returned. Default. aspx is the asp.net page to call the WebClient. UploadData method to submit data. The UploadDataWin project is called by the winform program.

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.