If 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 implement, the data you want to upload, you can simply, the program is simple:
String
Uristring
=
"
http://localhost/login.aspx
"
;
//
Create a new WebClient instance.
WebClient MyWebClient
=
New
WebClient ();
String
PostData
=
"
UserName = admin & password = admin
"
;
//
Pay attention to this spell string ContentType
MyWebClient.Headers.Add (
"
Content-Type
"
,
"
Application / X-WWW-FORM-URLENCODED
"
);
//
Transforming into binary arrays
Byte
[] ByteArray
=
Encoding.ascii.getbytes; postData
//
Upload data and get the returned binary data.
Byte
[] ResponseArray
=
MyWebClient.uploadData (uristring,
"
POST
"
ByteaRray;
For forms uploaded, for example (URL: http://localhost/uploadfile.aspx):
file
We can use this form
String uristring
=
"
Http://localhost/uploadfile.aspx
"
;
//
Create a new WebClient instance.
WebClient MyWebClient
=
New
WebClient ();
String
Filename
=
@ "
C: /upload.txt
"
;
//
Upload directly, and get the return binary data.
Byte
[] ResponseArray
=
MyWebClient.uploadFile (uristring,
"
POST
"
Filename;
There is also a form that not only has text, but also documents, such as (URL: http: //localhost/uploaddata.aspx):
File name file
For this form, it seems that the two methods seem to be applicable. For the first method, the strings cannot be spent directly. For the second, we can only pass the file, return to the first method, pay attention to the parameters:
Public Byte [] UPLOADDATA
String address,
String Method,
Byte [] DATA
);
In the first example, it is apparent to the BYTE [] Data parameter value by spelling a string. It is obviously not possible for this form. In turn thinking that for UPLOADDATA.ASPX, you will submit data directly through the web page. What is the stream obtained in the background? (In my previous blog, I have analyzed this question:
ASP-free component upload schedule solutions), the final data is as follows:
---------------------------- 7D429871607FEContent-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--
So just fight a such Byte [] Data data POST, you can achieve the same effect. But must pay attention to this file upload, which is different, such as the above, whose contentType is "Multipart / Form-Data; Boundary = ----------- ---------------- 7D429871607FE. With contenttype, we can know Boundary (above "---------------------- 7D429871607FE"), knowing Boundary, we will You can construct the Byte [] Data, final, don't forget, transfer our constructType to WebClient (for example, WebClient.Headers.Add ("Content-type", ContentType);) Upload the file data over the WebClient.uploadData method.
The specific code is as follows:
Generate a package of binary data classes
Using
System;
Using
System.Web;
Using
System.IO;
Using
System.net;
Using
System.Text;
Using
System.collections;
Namespace
UploadData.common
...
{
/ ** ////
/// Create a binary array required by WebClient.uploadData method
/// summary>
Public Class CreateBytes
... {
Encoding encoding = encoding.utf8;
/ ** ////
/// Splicing all the binary arrays are an array
/// summary>
/// array param>
///
///
Public Byte [] Joinbytes (ArrayList Byterrays)
... {
INT length = 0;
INT readLength = 0;
/ / Plus the end border
String endboundary = boundary "- / r / n"; // End the boundary
Byte [] endboundarybytes = Encoding.getbytes (Endboundary);
ByteaRrays.Add (endboundarybytes);
Foreach (byte [] b in byterrays) ... {Length = B.LENGTH;}
BYTE [] bytes = new byte [length];
// Traverse copy
//
Foreach (byte [] b in byterrays)
... {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.ress (); responsebytes = new byte [EX.RESPONSE.CONTENTLENGTH]; Resp.Read (responsebytes, 0, responsebytes.length);}
Return False;
}
/ ** ////
/// Get a common form area binary array
/// summary>
/// Table name param>
/// form value param>
///
///
/// ---------------------------- 7D52EE27210A3C / R / NCONTENT-DISPSITION: FORM-DATA; Name = / "table name / "/ R / N / R / N form value / R / N
/// remarks>
Public Byte [] CreatefieldData (String FieldName, String FieldValue)
... {
String textTemplate = Boundary "/ r / ncontent-disposition: form-data; name = /" {0} / "/ r / n / r / n {1} / r / n";
String text = string.format (TextTemplate, FieldName, FieldValue);
Byte [] bytes = encoding.getbytes (text);
Return Bytes;
}
/ ** ////
/// Get file uplink form single area binary array
/// summary>
/// Table name param>
/// file name param>
/// file type param>
/// file length param> /// file flow param>
///
Public Byte [] CreateFieldData (String FieldName, String FileName, String ContentType, Byte [] filebytes)
... {
String end = "/ r / n";
String textTemplate = Boundary "/ r / nContent-disposition: form-data; name = /" {0} / "; filename = /" {1} / "/ r / nContent-type: {2} / r / n / r / n ";
// head data
String Data = String.Format (TextTemplate, FieldName, FileName, ContentType);
Byte [] bytes = encoding.getbytes (data);
// Tail data
BYTE [] endbytes = encoding.getbytes (end);
// Composition after synthesis
Byte [] Fielddata = new byte [bytes.length filebytes.length endbytes.length];
Bytes.couthto (fielddata, 0); // head data
FileBytes.copyto (FieldData, Bytes.length); // Binary data
Endbytes.copyto (fielddata, bytes.length); // / r / n
Return Fielddata;
}
Property #Region property
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;}}
#ndregion
}
}
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
...
{
/ ** ////
/// frmupload's summary description.
/// 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;
/ ** ////
/// The required designer variable.
/// summary>
Private system.componentmodel.Container Components = NULL;
Public fmupload ()
... {
//
// Windows Form Designer Support
//
InitializationComponent ();
//
// Todo: Add any constructor code after INITIALIZECOMPONENT call
//
}
/ ** ////
/// Clean all the resources being used.
/// summary>
Protected Override Void Dispose (Bool Disposing)
... {
IF (Disposing)
... {if (Components! = NULL) ... {Components.dispose ();}}
Base.dispose (Disposing);
}
Windows Form Designer Generated Code #Region Windows Form Designer Generated Code
/ ** ////
Private vidinitiRizeComponent ()
... {this.lblamigotoken = new system.windows.forms.label (); this.txtamigotoken = new system.windows.forms.textbox (); this.lfilename = new system.windows.forms.label (); this .txtFilename = new System.Windows.Forms.TextBox (); this.btnBrowse = new System.Windows.Forms.Button (); this.txtFileData = 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.txtResponse = 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.txtAmigoToken.Location = new System.Drawing.Point (120, 48); this.txtamigotoken.name = "txtamigotoken"; this.txtAmigoToken.Size = new System.Drawing.Size (248, 21); this.txtAmigoToken.TabIndex = 1; this.txtAmigoToken.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.lfilename. Text = "filename"; // // txtFileName // this.txtFileName.Location = new system.drawing.point (120, 96); this.txtFileName.Name = "txtFileName"; this.txtFileName.Size = New System. Drawing.size (248, 21);
THISTXTFILENAME.TABINDEX = 3; this.txtFileName.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.TXTFILEDATA .Location = new system.drawing.point (120, 144); this.txtFileData.Name = "txtfileData"; this.txtFileData.size = new system.drawing.size (168, 21); this.txtFileData.tabindex = 5 THIS.TXTFILEDATA.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.lfileData.text = "filedata"; // // btnupload // this.btnupload.location = new system.drawing.point (48, 184); this.btnupload.name = "btnupload"; this.btnupload.tabindex = 7; this.btnupload.text = "UPL oad "; this.btnUpload.Click = new System.EventHandler (this.btnUpload_Click); // // txtResponse // this.txtResponse.Location = new System.Drawing.Point (136, 184); this.txtResponse.Multiline = True; this.txtResponse.name = "txtResponse"; this.txtResponse.size = new system.drawing.size (248, 72); this.txtResponse.tabindex = 8; this.txtResponse.text = ""; // // frMupload // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (400, 269);
This.Controls.add (this.txtResponse); this.controls.add (this.btnupload); this.controls.add (this.lblfiledata); this.controls.add (this.txtFileData); this.controls.add ( This.btnbrowse; this.txtFileName; this.controls.add (this.lblfilename); this.controls.add (this.txtamigotoken); this.controls.add (this.lblamigotoken); this .Name = "frmupload"; this.text = "frmupload"; this.ResumeLayout (false);} #ENDREGION
/ ** ////
/// The main entry point for the application.
/// summary>
[Stathread]
Static void main ()
... {
Application.run (New frmupload ());
}
Private void btnupload_click (Object Sender, System.Eventargs E)
... {
// Non-air test
IF (txtamigotoken.text.trim () == "" | TXTFILENAME.TEXT == "" || txtFileData.Text.trim () == "" "
... {MessageBox.show ("please fill data"; return;}
// The file path you want to upload
String path = txtfiledata.text.trim ();
/ / Check if the file exists
IF (! file.exists (path))
... {messagebox.show ("{0} does not exist!", Path); return;
// read file stream
FILESTREAM FS = New FileStream (path, filemode.open,
FileAccess.read, Fileshare.Read;
// This part needs improvement
String contentType = "Application / OcTet-stream";
Byte [] filebytes = new byte [fs.length];
fs.read (filebytes, 0, convert.toint32 (fs.length));
/ / Generate a binary array that needs to be uploaded
CreateBytes CB = New Createbytes ();
// All form data
ArrayList BytesArray = new arraylist ();
// ordinary 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));
/ / Synthesate all forms and generate binary arrays
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 content returned 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
annex:
UploadData.rar (38K), decompressed, build a virtual directory "UPLoadData" for the web directory, where UploadavaTar.aspx is the actual upload process page. If the upload is successful, return to the file name and file type. Default.aspx is an ASP.NET page to call the WebClient.uploadData method to submit data, and the UploadDataWin project is WinForm program call.