欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 07:58:04
如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用asp.net的作为代理是最好的办法,要是客户端直接提交到iframe中,由于跨域是无法用javascript获...

如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用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
://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;
      }
    }
  }
}