前言
基于MFC将本地文件(我上传的是csv文件)传到指定服务器 服务器http协议在将其放到protocol/upload_file.php路径下【免费】Http上传文件到服务器php文件资源-CSDN文库
1、MFC代码
void setHttpCSV(CString serverName,CString CSVPath){
CInternetSession session;
CHttpConnection* conn=NULL;
CString type;
CString boundary;
CString strData;
INTERNET_PORT m_port;
CHttpFile* Hfile;
CFile file;
DWORD totallength;
DWORD readlength;
DWORD neicun;
void* vd;
LPTSTR strerror;
m_port=80;
boundary=_T("-----46as7d----");
neicun=64*1024;
BOOL bRet = FALSE;
DWORD dwServiceType = 0;
CString strServer = _T("");
CString strObject = _T("");
INTERNET_PORT nPort = 0;
bRet = AfxParseURL(serverName, dwServiceType, strServer, strObject, nPort);
//CString filepath;
//CSVPath.GetWindowText(filepath);
CSVPath.Replace(L"\\",L"\\\\");
int nPos = CSVPath.ReverseFind('\\');
CString strFileName = CSVPath.Mid(nPos+1);
type = _T("Content-Type: text/csv\r\n");
type += _T("name: %s\r\n"); // 例如,用于OAuth 2.0的Bearer token
type += _T("boundary: %s\r\n"); // 自定义请求头
type += _T("\r\n"); // 请求头结束标记
//type=_T("Content-Type:text/csv;name:333.csv;boundary=%s\r\n");
strData.Format(type,strFileName,boundary);
if(!file.Open(CSVPath, CFile::modeRead | CFile::shareDenyWrite))
{
AfxMessageBox(_T("文件打开失败!"));
return;
}
totallength=file.GetLength();
try
{
conn = session.GetHttpConnection(strServer,nPort);
Hfile=conn->OpenRequest(CHttpConnection::HTTP_VERB_POST,strObject);
Hfile->AddRequestHeaders(strData);
Hfile->SendRequestEx(totallength, HSR_SYNC | HSR_INITIATE);
vd=malloc(neicun);
readlength=-1;
while (readlength!=0)
{
readlength=file.Read(vd,neicun);
if(readlength!=0)
{
Hfile->Write(vd,readlength);
}
}
}
catch (CException* e)
{
e->GetErrorMessage(strerror, MAX_PATH);
e->Delete();
AfxMessageBox(strerror);
Hfile->Close();
return;
}
Hfile->EndRequest(HSR_SYNC);
Hfile->Close();
delete Hfile;
file.Close();
session.Close();
if(vd!=NULL)
{
free(vd);
}
}
2、调用
CString serverName;
HTTP_IP(服务器IP)
serverName.Format(_T("http://%s:8060/protocol/upload_file.php"),HTTP_IP);
CString CSVPath;(本地文件路径)
setHttpCSV(serverName,CSVPath);