Asp.Net模拟表单提交数据和上传文件的实现代码

如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用Asp.Net的作为代理是最好的办法,要是客户端直接提交到iframe中,由于跨域是无法用javascript获取到iframe中返回的内容的。此时需要在自己的网站做一个动态页作为代理,将表单提交到动态页,动态页负责将表单的内容使用WebClient或HttpWebRequest将表单数据再上传到远程服务器,由于在服务器端进行操作,就不存在跨域问题了。

WebClient上传只包含键值对的文本信息示例代码:

代码如下:

string uriString = "http://localhost/login.aspx";
// 创建一个新的 WebClient 实例.
WebClient myWebClient = new WebClient();
string postData = "Username=admin&Password=admin";
// 注意这种拼字符串的ContentType
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// 转化成二进制数组
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
// 上传数据,并获取返回的二进制数据.
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);

WebClient上传只包含文件的示例代码:

代码如下:

String uriString = "http://localhost/uploadFile.aspx";
// 创建一个新的 WebClient 实例.
WebClient myWebClient = new WebClient();
string fileName = @"C:/upload.txt";
// 直接上传,并获取返回的二进制数据.
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

 对于既包含文件又包含文本键值对信息的示例代码,需要构造表单提交的内容,对于学asp的同学来说,下面的表单提交内容一定不会陌生

代码如下:

-----------------------------7d429871607fe
Content-Disposition: form-data; name="file1"; filename="G:/homepage.txt"
Content-Type: text/plain
我们:http://www.jb51.net
-----------------------------7d429871607fe
Content-Disposition: form-data; name="filename"
default filename
-----------------------------7d429871607fe--

  所以只要拼一个这样的byte[] data数据Post过去,就可以达到同样的效果了。但是一定要注意,对于这种带有文件上传的,其ContentType是不一样的,例如上面的这种,其ContentType为"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我们就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我们就可以构造出我们所需要的byte[] data了,最后,不要忘记,把我们构造的ContentType传到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)这样,就可以通过WebClient.UploadData 方法上载文件数据了。

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;
      // 加上结束边界
      string endBoundary = Boundary + "-- ";
      byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
      byteArrays.Add(endBoundaryBytes);
      foreach (byte[] b in byteArrays)
      {
        length += b.Length;
      }
      byte[] bytes = new byte[length];
      // 遍历复制
      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;
    }
    /// 获取普通表单区域二进制数组
    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} ";
      // 头数据
      string data = String.Format(textTemplate, fieldName, filename, contentType);
      byte[] bytes = encoding.GetBytes(data);
      // 尾数据
      byte[] endBytes = encoding.GetBytes(end);
      // 合成后的数组
      byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
      bytes.CopyTo(fieldData, 0); // 头数据
      fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
      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 = "浏览";
      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)
    {
      // 非空检验
      if (txtAmigoToken.Text.Trim() == "" || txtFilename.Text == "" || txtFileData.Text.Trim() == "")
      {
        MessageBox.Show("Please fill data");
        return;
      }
      // 所要上传的文件路径
      string path = txtFileData.Text.Trim();
      // 检查文件是否存在
      if (!File.Exists(path))
      {
        MessageBox.Show("{0} does not exist!", path);
        return;
      }
      // 读文件流
      FileStream fs = new FileStream(path, FileMode.Open,
        FileAccess.Read, FileShare.Read);
      // 这部分需要完善
      string ContentType = "application/octet-stream";
      byte[] fileBytes = new byte[fs.Length];
      fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
      // 生成需要上传的二进制数组
      CreateBytes cb = new CreateBytes();
      // 所有表单数据
      ArrayList bytesArray = new ArrayList();
      // 普通表单
      bytesArray.Add(cb.CreateFieldData("FileName", txtFilename.Text));
      bytesArray.Add(cb.CreateFieldData("AmigoToken", txtAmigoToken.Text));
      // 文件表单
      bytesArray.Add(cb.CreateFieldData("FileData", path
                        , ContentType, fileBytes));
      // 合成所有表单并生成二进制数组
      byte[] bytes = cb.JoinBytes(bytesArray);
      // 返回的内容
      byte[] responseBytes;
      // 上传到指定Url
      bool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes);
      // 将返回的内容输出到文件
      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;
      }
    }
  }
}
(0)

相关推荐

  • Asp.Net的FileUpload类实现上传文件实例

    本文实例讲述了Asp.Net的FileUpload类实现上传文件的方法.分享给大家供大家参考. 具体功能代码如下: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web; using System.Web.UI.WebControls; using System.Collections; using System.Dra

  • Asp.net MVC中使用JQuery插件ajaxFileUpload上传文件

    0 ajaxFileUpload简介 ajaxFileUpload插件是一个非常简单的基于Jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比较多,我把我自己使用的ajaxFileUpload文件上传到博客园上了,想要使用的朋友可以下载:http://xiazai.jb51.net/201611/yuanma/ajaxfileupload(jb51.net).rar. 整个插件源码不到200行,实现非常简单,大致原理就是通过js动态创建隐

  • asp.net 模拟提交有文件上传的表单(通过http模拟上传文件)

    我们暂且不说如何去模拟数据,通过一个简单的form看看当请求发生时,客户端提交了什么样的数据给服务端. 下面是一个简单的html form,两个文本输入框,一个文件上传(这里我选择一张图片),注意有文件上传的form的enctype属性. 复制代码 代码如下: <form action="sql.aspx" method="post" enctype="multipart/form-data"> <input id="

  • asp.net实现上传文件显示本地绝对路径的实例代码

    页面代码主要就是JSview plaincopy to clipboardprint 复制代码 代码如下: <head runat="server">     <title>无标题页</title>     <mce:script language="javascript" type="text/javascript"><!--      function Imagesrc()      { 

  • asp.net中MVC借助Iframe实现无刷新上传文件实例

    本文实例讲述了asp.net中MVC借助Iframe实现无刷新上传文件的方法.分享给大家供大家参考.具体实现方法如下: html: 复制代码 代码如下: <div id="uploadwindow" style="display: none;">     <form action="/ShopActivitys/ImportActivityItems" id="form1" name="form1&

  • asp.net上传文件到数据库的解决方案

    现在,我们来看存放文件的数据库表结构,这里,我们给出建立表的标准SQL语句: CREATE TABLE tblBooksUpload ( DocID int NOT NULL IDENTITY Primary Key , DocTitle varchar (200) , Doc image, DocType varchar (50) , Entrydate datetime Default GetDate() ) 以上的语句中,我们看到数据表tblBooksUpload包含五个字段: ·字段Do

  • 如何限制asp.net中上传文件的大小的代码

    在web.config中控制上传文件大小的地方: 复制代码 代码如下: <system.web><httpRuntime executionTimeout="9999" maxRequestLength="2097151"/></system.web> maxRequestLength是控制上传大小得参数请求的最大大小(以千字节为单位).默认大小为 4096 KB (4 MB).ExecutionTimeout 指示在请求被 AS

  • ASP.NET插件uploadify批量上传文件完整使用教程

    uploadify批量上传文件完整使用教程,供大家参考,具体内容如下 1.首先准备uploadify的js文件,网上一搜一大堆 2.上传页面UpFilePage.aspx 关键代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/h

  • Asp.Net修改上传文件大小限制方法

    话不多说,随小编一起看看下面代码吧 i. Configuration节点下 <system.webServer> <security> <requestFiltering> <!--单位为字节 maxAllowedContentLength--> <requestLimits maxAllowedContentLength="2097151000"/> </requestFiltering> </securi

  • asp.net fileupload控件上传文件与多文件上传

    1.前台文件 Default.aspx: <%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.

  • 解决.net项目中上传的图片或者文件太大无法上传问题

    最近做项目的时候  用户提出要上传大图片  一张图片有可能十几兆  本来用的第三方的上传控件  有限制图片上传大小的设置 以前设置的是2M  按照用户的要求  以为直接将限制图片上传大小的设置改下就可以了  但是当上传大图片的时 总是异常: 错误消息:超过了最大请求长度 解决方案: 错误原因:asp.net默认最大上传文件大小为4M,运行超时时间为90S. 修改web.config中配置 <configuration> <system.web> <httpRuntime us

随机推荐