ASP.net simulation form submission data and upload file implementation code _ Practical skills

Source: Internet
Author: User
Tags httpcontext trim

If you need to upload content across the domain to another domain name and need to get the return value, use ASP.net as the proxy is the best way, if the client directly submitted to the IFRAME, because Cross-domain can not use JavaScript to get the content returned in the IFRAME. At this point, you need to do a dynamic page as a proxy, the form submitted to the dynamic page, the dynamic page is responsible for the content of the form to use WebClient or HttpWebRequest to upload the form data to the remote server, because the server side of the operation, there is no cross-domain problem.

WebClient upload sample code that contains only key-value pairs for text messages:

Copy Code code 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 this spelling string
MYWEBCLIENT.HEADERS.ADD ("Content-type", "application/x-www-form-urlencoded");
Convert into binary array
byte[] ByteArray = Encoding.ASCII.GetBytes (postdata);
Upload the data and get the binary data returned.
byte[] Responsearray = Mywebclient.uploaddata (uristring, "POST", ByteArray);

WebClient upload sample code that contains only files:

Copy Code code as follows:

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 binary data returned.
byte[] Responsearray = Mywebclient.uploadfile (uristring, "POST", fileName);

For example code that contains both files and text key value pairs, you need to construct the content of the form submission, and for students studying ASP, the following form submission must not be unfamiliar

Copy Code code as follows:

-----------------------------7d429871607fe
Content-disposition:form-data; Name= "File1"; Filename= "G:/homepage.txt"
Content-type:text/plain
Cloud-dwelling community: http://www.jb51.net
-----------------------------7d429871607fe
Content-disposition:form-data; Name= "FileName"
Default filename
-----------------------------7d429871607fe--

So as long as one such byte[] data post the past, you can achieve the same effect. However, it must be noted that for this file upload, its contenttype is not the same, such as the above, its contenttype as "MULTIPART/FORM-DATA;" boundary=---------------------------7d429871607fe ". With contenttype, we can know boundary (the "---------------------------7d429871607fe" above), knowing boundary we can construct the byte[we need. Data, and, finally, don't forget to pass our constructed ContentType to WebClient (for example: WebClient.Headers.Add ("Content-type", ContentType); You can upload file data through the Webclient.uploaddata method.

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;
      Plus end boundary string endboundary = Boundary + "--"; byte[] endboundarybytes = encoding.
      GetBytes (endboundary);
      Bytearrays.add (endboundarybytes);
      foreach (byte[] b in bytearrays) {length + = B.length;
      } byte[] bytes = new Byte[length];
        Traversal replication 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 = n
      EW WebClient ();
      WEBCLIENT.HEADERS.ADD ("Content-type", ContentType); try {Responsebytes = webclient.uploaddata (Uploadurl, bytes);
      return true; The catch (WebException ex) {Stream resp = ex.
        Response.getresponsestream (); ResponseBytes = new Byte[ex.
        Response.contentlength]; Resp.
      Read (responsebytes, 0, responsebytes.length);
    return false; ///get normal form area binary array public byte[] Createfielddata (String fieldName, String fieldvalue) {string texttemp Late = 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) {s
      Tring end = ""; String texttemplate = boundary + "Content-disposition:form-data;" Name= "{0}";
      Filename= ' {1} ' Content-type: {2} '; Header Data String = String.Format (texttemplate, fieldName, filename, contenTtype); byte[] bytes = encoding.
      GetBytes (data); Tail data byte[] endbytes = encoding.
      GetBytes (end); The synthesized array byte[] Fielddata = new byte[bytes.
      Length + filebytes.length + endbytes.length]; bytes. CopyTo (fielddata, 0); Header Data Filebytes.copyto (Fielddata, bytes. Length); File binary Data endbytes.copyto (Fielddata, bytes. Length + filebytes.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;
        boundary=---------------------------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
    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;
    Private System.ComponentModel.Container components = null;
    Public Frmupload () {InitializeComponent ();} protected override void Dispose (bool disposing) {if (disposing) {if (Components!= null) {Components.
        Dispose (); } base.
    Dispose (disposing);
      private void InitializeComponent () {This.lblamigotoken = new System.Windows.Forms.Label ();
      This.txtamigotoken = new System.Windows.Forms.TextBox ();
      This.lblfilename = 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.lblFilename.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);
      This.txtFilename.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 = "browsing";
      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.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.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.Controls.Add (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);
    [STAThread] static void Main () {Application.Run (New frmupload ()); } private void Btnupload_click (object sender, System.EventArgs e) {//Non-empty check if (txtAmigoToken.Text.Tri m () = = "" | | Txtfilename.text = "" | |
        TxtFileData.Text.Trim () = = "") {MessageBox.Show ("Please fill data");
      Return
      //The file path 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 section needs to be perfected by string ContentType = "Application/octet-stReam "; byte[] filebytes = new Byte[fs.
      Length]; Fs. Read (filebytes, 0, Convert.ToInt32 (FS).
      Length));
      Generate a binary array to upload createbytes cb = new Createbytes ();
      All form data ArrayList Bytesarray = new ArrayList (); General Form Bytesarray.add (CB.
      Createfielddata ("FileName", Txtfilename.text)); Bytesarray.add (CB.
      Createfielddata ("Amigotoken", Txtamigotoken.text)); Document Form Bytesarray.add (CB.
      Createfielddata ("Filedata", Path, ContentType, filebytes)); Synthesis of all forms and generation of binary arrays byte[] bytes = cb.
      Joinbytes (Bytesarray);
      The content returned byte[] responsebytes; Upload to the specified URL bool uploaded = cb.
      Uploaddata ("http://localhost/UploadData/UploadAvatar.aspx", Bytes, out responsebytes); Outputs the returned content to the file using (FileStream file = new FileStream (@ "C:esponse.text", FileMode.Create, FileAccess.Write, Filesh are. 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 () = = Dial
      Ogresult.ok) {txtfiledata.text = Openfiledialog1.filename; }
    }
  }
}

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.