因为项目的需要,需要做一个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>
<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");
}
}