1、在C++Builder6 Update4中安装好Indy10,可以在www.ccrun.com中找到Indy10的安装包及安装方法;
2、 在C++Builder6中建立一个新的Application,在Form上放置一个IdHTTP组件,再放置一个Button组件,在Button组件的OnClick事件中写入如下代码:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TIdStringStream* ResponseStream = new TIdStringStream(NULL);
TIdMultiPartFormDataStream* PostStream = new TIdMultiPartFormDataStream();
TIdStringList* UploadFile = new TIdStringList();
try{
UploadFile->Values["UpFile"] = "c:\test.doc"; //假设需要上传的文件为C盘根目录下的test.doc
IdHTTP1->Request->ContentType = PostStream->RequestContentType;
PostStream->AddFile("UpFile",UploadFile->Values["UpFile"],GetMIMETypeFromFile(UploadFile->Values["UpFile"]));
IdHTTP1->Post("http://localhost/", PostStream, ResponseStream);
}
__finally
{
delete UploadFile;
delete PostStream;
delete ResponseStream;
}
}
3、如果想加上进度条,还可以在Form上放置一个ProgressBar组件,然后再分别在IdHTTP组件的OnWorkBegin和OnWork两个事件中写入如下代码:
void __fastcall TForm1::IdHTTP1WorkBegin(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCountMax)
{
ProgressBar1->Min = 0;
ProgressBar1->Max = AWorkCountMax;
}
void __fastcall TForm1::IdHTTP1Work(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
ProgressBar1->Position = ProgressBar1->Position + AWorkCount;
}
这样就可以模拟HTML中Input的File来进行文件上传了,还可以继续完善这个功能,例如选择文件(可以利用OpenDialog组件)。当然,把这个转换成ActiveX,运行在客户端IE中,那就更加方便了。