Asp. Net simulates the implementation code for the form to submit data and upload files

  • 2020-12-26 05:39:01
  • OfStack

If you need to upload content across domains to another domain and need to get the return value, using Asp.Net as a proxy is the best way to do this. If the client submits the content directly to iframe, it is not possible to use javascript to get the returned content across domains. At this time, I need to make a dynamic page on my own website as a proxy to submit the form to the dynamic page, which is responsible for using WebClient or HttpWebRequest to upload the form data to the remote server. Since I operate on the server side, there is no cross-domain problem.

WebClient uploads sample code for text messages containing only key-value pairs:


string uriString = "http://localhost/login.aspx";
// create 1 A new one WebClient The instance .
WebClient myWebClient = new WebClient();
string postData = "Username=admin&Password=admin";
// Notice the spelling of the string ContentType
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// Converted into 2 Hexadecimal array
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
// Upload the data and get the returned one 2 Hexadecimal data .
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);

Sample code for WebClient upload containing only files:


String uriString = "http://localhost/uploadFile.aspx";
// create 1 A new one WebClient The instance .
WebClient myWebClient = new WebClient();
string fileName = @"C:/upload.txt";
// Upload directly and get the returned 2 Hexadecimal data .
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

For example code that contains both file and text key-value pair information, you need to construct the content of the form submission. For those of you studying asp, the following form submission content 1 will be familiar


-----------------------------7d429871607fe
Content-Disposition: form-data; name="file1"; filename="G:/homepage.txt"
Content-Type: text/plain
Home of Scripts: https://www.ofstack.com
-----------------------------7d429871607fe
Content-Disposition: form-data; name="filename"
default filename
-----------------------------7d429871607fe--

So just spell one of these byte[] data data Post past to achieve the same effect. However, it should be noted that the ContentType is not the same as the one with file upload. For example, the ContentType is "multipart/ ES34en-ES35en. boundary = -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 7 d429871607fe ". With ContentType, we can know boundary, know boundary we can construct byte[] data, and finally, don't forget, Transfer the ContentType we constructed to WebClient (for example: webClient.Headers.Add (" Content-Type ", ContentType);) This allows the file data to be uploaded via 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 the 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];
      //  Traverse the 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;
    }
    ///  Gets the normal form area 2 Hexadecimal 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} ";
      //  The first data 
      string data = String.Format(textTemplate, fieldName, filename, contentType);
      byte[] bytes = encoding.GetBytes(data);
      //  Mantissa according to 
      byte[] endBytes = encoding.GetBytes(end);
      //  The resulting array 
      byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
      bytes.CopyTo(fieldData, 0); //  The first data 
      fileBytes.CopyTo(fieldData, bytes.Length); //  Of the file 2 Hexadecimal 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 = " 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.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)
    {
      //  Not empty inspection 
      if (txtAmigoToken.Text.Trim() == "" || txtFilename.Text == "" || txtFileData.Text.Trim() == "")
      {
        MessageBox.Show("Please fill data");
        return;
      }
      //  The path to the file 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 the file stream 
      FileStream fs = new FileStream(path, FileMode.Open,
        FileAccess.Read, FileShare.Read);
      //  This part needs to be perfected 
      string ContentType = "application/octet-stream";
      byte[] fileBytes = new byte[fs.Length];
      fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
      //  Generate what needs to be uploaded 2 Hexadecimal array 
      CreateBytes cb = new CreateBytes();
      //  All form data 
      ArrayList bytesArray = new ArrayList();
      //  Common 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 them 2 Hexadecimal array 
      byte[] bytes = cb.JoinBytes(bytesArray);
      //  The content returned 
      byte[] responseBytes;
      //  Upload to designated Url
      bool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes);
      //  Outputs the returned content to a 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;
      }
    }
  }
}


Related articles: