Asp. Net simulates the implementation code of Form submission data and file upload, asp.net form
If you need to upload content across domains to another domain name and obtain the returned value, use Asp. net is the best way to act as a proxy. If the client is directly submitted to the iframe, the cross-origin cannot use javascript to obtain the content returned by iframe. In this case, you need to create a dynamic page on your website as a proxy to submit the form to the dynamic page. The dynamic page is responsible for uploading the form data to the remote server using WebClient or HttpWebRequest, the operation on the server does not cause cross-origin problems.
Sample Code of WebClient uploading text information that only contains key-value pairs:
Copy codeThe Code is as follows:
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 );
WebClient uploads sample code that only contains files:
Copy codeThe Code is as follows:
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 );
For sample code that contains both files and text key-value pairs, You need to construct the content submitted by the form. For asp students, the content submitted by the following form is certainly not unfamiliar.
Copy codeThe Code is as follows:
----------------------------- 7d429871607fe
Content-Disposition: form-data; name = "file1"; filename = "G:/homepage.txt"
Content-Type: text/plain
Helping House: http://www.bkjia.com
----------------------------- 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.
Using System; using System. web; using System. IO; using System. net; using System. text; using System. collections; namespace UploadData. common {public class CreateBytes {Encoding encoding = Encoding. UTF8; public byte [] JoinBytes (ArrayList byteArrays) {int length = 0; int readLength = 0; // Add the end Boundary string endBoundary = Boundary + "--"; byte [] endBoundaryBytes = encoding. getBytes (endBoundary); byteArrays. ad D (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); t Ry {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;} // obtain the binary array public byte [] CreateFieldData (string fieldName, string fieldValue) {string textTemplate = Boundary + "Content -Disposition: form-data; name = "{0}" {1} "; string text = String. format (textTemplate, fieldName, fieldValue); byte [] bytes = encoding. getBytes (text); return bytes;} public byte [] CreateFieldData (string fieldName, string filename, string contentType, byte [] fileBytes) {string end = ""; string textTemplate = Boundary + "Content-Disposition: form-data; name =" {0} "; filename =" {1} "Content-Type: {2} "; // Header data string data = String. format (textTemplate, fieldName, filename, contentType); byte [] bytes = encoding. getBytes (data); // The last data byte [] endBytes = encoding. getBytes (end); // The merged array byte [] fieldData = new byte [bytes. length + fileBytes. length + endBytes. length]; bytes. copyTo (fieldData, 0); // fileBytes header data. copyTo (fieldData, bytes. length); // The binary data of the file endBytes. copyTo (fieldData, bytes. length + fi LeBytes. length); // return fieldData;} 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; B Oundary = --------------------------- 7d5b915500cee ";} return HttpContext. current. request. contentType ;}}} 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 {public class frmUpload: System. windows. forms. form {private System. windows. forms. label lblAmigo Token; 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 openFil EDialog1; private System. windows. forms. textBox txtResponse; private System. componentModel. container components = null; public frmUpload () {InitializeComponent ();} protected override void Dispose (bool disposing) {if (components! = Null) {components. dispose () ;}} base. dispose (disposing);} 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 = "lblAmigoToke N "; 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 = ""; // lblF Ilename // 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. drawin G. size (248, 21); this.txt Filename. tabIndex = 3; this.txt Filename. text = ""; // btnBrowse // this. btnBrowse. location = new System. drawing. points (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, 1 44); 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. points (40,144); this. lblFileData. name = "lblFileData"; this. lblFileData. size = new System. drawing. size (72, 23); this. lblFileData. tabIndex = 6; this. lblFileData. text = "Fil EData "; // btnUpload // this. btnUpload. location = new System. drawing. points (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 FileD Ata); 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);} [STAThread] static void Main () {Application. run (new frmUpload ();} private void btnUpload_Click (object sender, System. eventArgs E) {// non-null check if (txtAmigoToken. text. trim () = "" | txtFilename. text = "" | txtFileData. text. trim () = "") {MessageBox. show ("Please fill data"); return;} // path of the file to be uploaded: string path = txtFileData. text. trim (); // check whether the object 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 by 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 (); // The 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); // synthesize 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: esponse. 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 ;}}}}
How to receive data submitted by forms in aspnet in the background (post submission)
Take a closer look at your code. The input id is UserName and Pwd, but to get the form content, you must get it through the name attribute of the corresponding control in the form. Do you understand?
Change it to <input name = "UserName type ="... "/> and Request. Form [" UserName "]. ToString ();
In this way, you can
C # simulate Form submission using code and upload XML files at the same time
I don't know.
One stupid way is to generate js code in the background. The function of this js Code is to generate a form and then let this js Code trigger the form submission event.