其他分享
首页 > 其他分享> > 利用libcurl库实现post数据上传

利用libcurl库实现post数据上传

作者:互联网

具体用例可以从postman进行复制,比较方便,后台接口api写好以后,在postman运行,然后点击右侧编辑按钮,下拉框选择C-libcurl,下面会自动显示出示例代码:
在这里插入图片描述


struct fileInfo  
{  
	fileInfo()
	{
	}

	fileInfo::fileInfo(const fileInfo& other)
	{
		strFilePath = other.strFilePath;
		strFileDir = other.strFileDir;
	}

	fileInfo& operator = (fileInfo& thInfo)
	{
		strFilePath = thInfo.strFilePath;
		strFileDir = thInfo.strFileDir;

		return* this;
	}

	~fileInfo()
	{

	}

	wstring strFilePath;
	wstring strFileDir;
};  


bool CurlPostFile(LPCTSTR sUrl, LPCTSTR sToken,LPCTSTR sProjectId,bool bZip,std::vector<fileInfo> vecFileInfo,int& nStatus)
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();
	if(curl == nullptr)
	{
		return false;
	}

	curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
	curl_easy_setopt(curl, CURLOPT_URL, sUrl);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "http");

	struct curl_slist *headers = NULL;
	headers = curl_slist_append(headers, sToken);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
	curl_mime *mime;
	curl_mimepart *part;
	mime = curl_mime_init(curl);

	for (auto iterFile = vecFileInfo.begin(); iterFile != vecFileInfo.end(); ++iterFile)
	{
		wstring wsAbsFileName = iterFile->strFilePath;
		part = curl_mime_addpart(mime);
		curl_mime_name(part, "files");
		string sFilePath = UnicodeToUtf8(wsAbsFileName);
		curl_mime_filedata(part, sFilePath.c_str());
	}

	string sFilePaths;
	for (int i = 0; i < vecFileInfo.size(); ++i)
	{
		wstring wsDir = vecFileInfo[i].strFileDir;
		string sDir = UnicodeToASNI(wsDir.c_str());
		sDir = "\"" + sDir + "\"";

		if (i != vecFileInfo.size() - 1)
		{
			sFilePaths = sFilePaths + sDir + ",";
		}
		else
		{
			sFilePaths = sFilePaths + sDir;
		}
	}

	sFilePaths = "[" + sFilePaths + "]";
	ReplaceString(sFilePaths, "\\", "/");
	wstring wsFilePaths = ANSIToUnicode(sFilePaths);
	string sUTF8Paths = UnicodeToUtf8(wsFilePaths);

	std::wstring wsFilesDir;
	part = curl_mime_addpart(mime);
	curl_mime_name(part, "filePaths");
	curl_mime_data(part, sUTF8Paths.c_str(), CURL_ZERO_TERMINATED);

	part = curl_mime_addpart(mime);
	curl_mime_name(part, "projectId");
	curl_mime_data(part, sProjectId, CURL_ZERO_TERMINATED);

	part = curl_mime_addpart(mime);
	curl_mime_name(part, "needUnZip");
	if (bZip)
	{
		curl_mime_data(part, "true", CURL_ZERO_TERMINATED);
	}
	else
	{
		curl_mime_data(part, "false", CURL_ZERO_TERMINATED);
	}

	curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
	res = curl_easy_perform(curl);
	curl_mime_free(mime);

	curl_easy_cleanup(curl);

	nStatus = (int)res;

	if (res != CURLE_OK)
	{
		return false;
	}

	return true;
}

标签:libcurl,sFilePaths,part,mime,easy,post,fileInfo,上传,curl
来源: https://blog.csdn.net/m0_37251750/article/details/123082482