c++ builder 写WinForm上传文件至Web服务器

因为项目的需要,需要做一个WinForm上传文件到Web服务端,其中WinForm用C++Builder2010编写,Web服务出来端用C#编写,弄了好久终于可以了,代码如下:

WinForm:

UnicodeString templateSavePath = ChangeFileExt(ExtractFilePath(Application->ExeName),"tmp_1.doc");
 TIdMultiPartFormDataStream *stream = new TIdMultiPartFormDataStream();
 TIdHTTP *http = new TIdHTTP(NULL);
 try{
  stream->AddFormField("FileUpload1","file"); //file与处理input名称一致
  stream->AddFile("FileUpload1", templateSavePath, "multipart/form-data");
  stream->Position = 0;
  stream->AddFormField("__VIEWSTATE", "/wEPDwUKLTQwMjY2MDA0Mw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkPSvKmhcE2B/KPSCtJymHckqFiPw=");
  stream->AddFormField("__EVENTVALIDATION", "/wEWAgLJnM/wAgKM54rGBpzhFrVYlwBNyjJVUCW6bwMJeJQb");
  stream->AddFormField("Button1", "Button");
  IdAntiFreeze1->OnlyWhenIdle = false;
  http->Request->ContentType = "multipart/form-data";
  UnicodeString result = http->Post("http://localhost:1723/upload_tmp/Default.aspx", stream);
  if (result == "ok") {
   //MessageDlg("文件上传成功!", mtInformation, mbOK, 0);
  } else {
   //MessageDlg("文件上传失败!", mtInformation, mbOK, 0);
  }
 }__finally{
  delete stream;
  delete http;
 }

客户端需要添加几个asp.net特有的域:__VIEWSTATE及__EVENTVALIDATION,他们的值可以打开asp.net页面复制一个,然后还有加上Button的域及FileUpload组件的域就可以了

 

Web服务端:

default.aspx

form id="form1" runat="server">
    <div>
        &nbsp;<asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    </form>

default.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.FileUpload1.FileBytes.Length > 0)
            {
                string savePath = Server.MapPath("~/" + Path.GetFileName(FileUpload1.FileName));
                for (int i = 0; i < this.Request.Files.Count; ++i)
                {
                    this.Request.Files[i].SaveAs(savePath);
                }
                Response.Clear();
                Response.Write("ok");
            }
        }
        catch
        {
            Response.Write("no");
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值