在postman 中使用POST----》body----》form-data
使用libcurl提交代码方式:
结构体:
#define MAX_ARRAY_SIZE 5*1024*1024
struct SMART_DATA_CACHE
{
char* buf;
long dwTotalLen;
SMART_DATA_CACHE()
{
dwTotalLen = 0;
buf = nullptr;
while (!buf) {
try {
buf = new char[MAX_ARRAY_SIZE];
}
catch (...) {}
}
memset(buf, 0x00, MAX_ARRAY_SIZE);
}
~SMART_DATA_CACHE()
{
if (buf) {
delete[] buf;
buf = nullptr;
dwTotalLen = 0;
}
}
};
接收回调:
size_t ManageCurl::http_recv_cb(void* ptr, size_t size, size_t nmemb, void* stream)
{
SMART_DATA_CACHE* pDataBuf = (SMART_DATA_CACHE*)stream;
if (pDataBuf) {
if (pDataBuf->buf) {
if (pDataBuf->dwTotalLen + size * nmemb < MAX_ARRAY_SIZE) {
memcpy(pDataBuf->buf + pDataBuf->dwTotalLen, ptr, size * nmemb);
pDataBuf->dwTotalLen += size * nmemb;
}
}
}
return size * nmemb;
}
调用:
CURL* curl = curl_easy_init();
if (curl) {
struct curl_slist* http_header = NULL;
/* 填充文件上传字段 */
curl_mime* form = curl_mime_init(curl);
curl_mimepart* field = curl_mime_addpart(form);
curl_mime_name(field, "file");
curl_mime_filedata(field, "d:\\2024_08_13_11_14_17.991.mp4");//需要注意中文路径
//http_header = curl_slist_append(http_header, "Expect:");
//http_header = curl_slist_append(http_header, "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3");
http_header = curl_slist_append(http_header, "Charset: UTF-8");
http_header = curl_slist_append(http_header, "Connection: keep-alive");//保持长连接
http_header = curl_slist_append(http_header, "Content-Type:multipart/form-data");//保持长连接
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);//修改协议头
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, http_recv_cb);//设置接收回调
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&stRecv);//设置设置参数
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);//设置连接时的超时时间为5秒
curl_easy_setopt(curl, CURLOPT_TIMEOUT, nTimeout);//超时秒为单位
curl_easy_setopt(curl, CURLOPT_URL, pUrl);//指定URL
curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
CURLcode res = curl_easy_perform(curl);//执行
long nRet = 0;
CURLcode codeRet = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &nRet);
if (codeRet == CURLE_OK && nRet == 200) {
bResult = true;
}
curl_easy_cleanup(curl);
curl_mime_free(form);
curl_slist_free_all(http_header);
}
这里需要注意:
- Content-Type为 multipart/form-data
2.curl_easy_setopt(curl, CURLOPT_POST, 1L); 不需要指定,所以不需要添加该语句
3.下面这段代码上传不行
curl_easy_setopt(curl, CURLOPT_READFUNCTION, http_read_cb);
curl_easy_setopt(curl, CURLOPT_READDATA, pFile);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)stFileInfo.st_size);
- 下面这句代码也不行
curl_formadd((curl_httppost**)&formpost,
(curl_httppost**)&lastptr,
CURLFORM_COPYNAME, "File1",
CURLFORM_FILE, "d://进步.txt",
CURLFORM_FILENAME, pUrlName,
CURLFORM_END);