这两天做个项目,使用http协议,之前也带有文件的上传,但是之前都把文件经过base64加密后,文件数据和要发送的数据拼在一块上传;http协议头的Content-Type: text/json,也就是将数据组成一个json串发送出去。(PS,json是如下的类型的数据{“name":"dyt", "name":"25"} )
但现在文件数据不经过base64加密的了,要使用Content-Type 为”multipart/form-data”来上传多个文件附近。这样我就搜了网上的不少资料,的确有了不少的帮助效果。而一个高手通过jmeter来实现客户的效果,来达到文件上传的。
如下图jmeter的操作和实现的效果:
点击jmeter的运行之后 ,可以看到请求的body和header
header如下:
看了如上,也是使用text/json的形式来上传数据 。那么编写代码就如下,不过风格有点类似于Content-Type 为”multipart/form-data”的情况。
代码实现部分:
void MakeFormDataBody(CString c_json, UploadFileMap filemap)
{
string str_formdata;
int i = 0;
m_sndbody.clear(); //先清空上次的内容
str_formdata.clear(); ////先清空上次的内容
if (filemap.empty())
{
str_formdata = "Content-Disposition: form-data; name=\"data\"";
m_sndbody += "--pzfIMNg-lMqY8r_sbn1N0RUhWY7i_ypCs\r\n" + str_formdata + "\r\n";
m_sndbody += "Content-Type: text/plain; charset=UTF-8";
m_sndbody += "\r\n";
m_sndbody += "Content-Transfer-Encoding: 8bit";
m_sndbody += "\r\n\r\n";
m_sndbody += c_json;
m_sndbody += "\r\n";
m_sndbody +="--pzfIMNg-lMqY8r_sbn1N0RUhWY7i_ypCs--\r\n";
}
else
{
string mine_type;
string filename;
string filecontent;
UploadFileMap::iterator it;
str_formdata = "Content-Disposition: form-data; name=\"data\"";
m_sndbody += "--pzfIMNg-lMqY8r_sbn1N0RUhWY7i_ypCs\r\n" + str_formdata + "\r\n";
m_sndbody += "Content-Type: text/plain; charset=UTF-8";
//m_sndbody += "\r\n";
//m_sndbody += "Content-Transfer-Encoding: 8bit";
m_sndbody += "\r\n\r\n";
m_sndbody += c_json;
m_sndbody += "\r\n";
it = filemap.begin();
for (; it!=filemap.end(); it++)
{
str_formdata.clear();
mine_type.clear();
filename.clear();
filecontent.clear();
str_formdata = "--pzfIMNg-lMqY8r_sbn1N0RUhWY7i_ypCs\r\n";
str_formdata += "Content-Disposition: form-data; ";
filename = (*it).name;
mine_type = (*it).mine_type;
filecontent = (*it).file_content;
str_formdata += "name=\"" + filename + "\"; ";
str_formdata += "filename=\"" + filename + "\"" + "\r\n";
str_formdata += "Content-Type: " + mine_type + "\r\n";
str_formdata += "\r\n";
//str_formdata += "Content-Transfer-Encoding: binary";
//str_formdata += "\r\n\r\n";
//str_formdata += "\"" + filecontent + "\"" + "\r\n";
str_formdata += filecontent;
str_formdata += "\r\n";
m_sndbody += str_formdata;
}
m_sndbody += "--pzfIMNg-lMqY8r_sbn1N0RUhWY7i_ypCs--";
m_sndbody += "\r\n";
}
注:m_sndbody就是最后发送http请求时的body,类似上图中的request body。
UploadFileMap是个结构体,因为传文件的话,要传文件的名称,文件的mine_type,文件的内容(也就是二进制)。
该结构 体如下:
struct FileAttrib
{
std::string name;
std::string mine_type;
std::string file_content;
};
typedef std::vector<FileAttrib> UploadFileMap;