//cgicc文件上传封装
void UploadSoftware()
{// 初始化CGIC环境Cgicc cgi;// 获取上传的文件file_iterator fileIter = cgi.getFile("button_browse"); //from表单中,输入为文件属性(type=file)的name属性值if (fileIter == cgi.getFiles().end()){
#if (DEBUG == true)cout << "file: " << cgi.getFiles().size() << endl;
#endif}else{FormFile& file = *fileIter;
#if (DEBUG == true)std::cout << "<p>file: " << std::endl;std::cout << "<br> name: "<< file.getName() << std::endl;std::cout << "<br> filename: "<< file.getFilename() << std::endl;std::cout << "<br> type: "<< file.getDataType() << "; cgicc::HTTPHTMLHeader=" << cgicc::HTTPHTMLHeader() << std::endl;std::cout << "<br> size: "<< file.getDataLength() << std::endl;std::cout << "<br> content: "<< file.getData() << std::endl;
#endif// 保存文件到服务器指定路径ofstream outfile("/opt/software/" + file.getFilename(), ios::out | ios::binary);outfile << file.getData();outfile.close();}
}
<!--html from表单部分-->
<script>
function SubmitUpgrade(obj)
{if(document.getElementById("button_browse").value == "" && document.getElementById("software_bag_url").value == ""){alert("软件升级包未选中");return false;}var ip_pos = radio_json.base.localHost.split('.');var first_ip_pos = Number(ip_pos[3]) + 100;var second_ip_pos = Number(ip_pos[3]) + 200;var first_ip = ip_pos[0] + "." + ip_pos[1] + "." + ip_pos[2] + "." + first_ip_pos;var second_ip = ip_pos[0] + "." + ip_pos[1] + "." + ip_pos[2] + "." + second_ip_pos;console.log("first_ip=" + first_ip + "; second_ip=" + second_ip + "; third=" + radio_json.base.localHost);obj.action="/cgi-bin/uphold_tools/uphold_tools.cgi?upgrade_software&1&" + first_ip + "&" + second_ip + "&" + radio_json.base.localHost + "&client&1";obj.submit();
}
</script>
<form enctype="multipart/form-data" id="form_upgrade" name="form_upgrade" method="post"><td class="css12r">软件升级包:</td><td><input name="software_bag_url" type="text" id="software_bag_url" size="22" maxlength="22" /></td><td><p class="css12l"><input type="file" name="button_browse" id="button_browse" /></p></td><td><p class="css12l"><input type="submit" name="button_upgrade" id="button_upgrade" value="升级" onclick="return SubmitUpgrade(this.form)"/></p></td>
</form>
测例:
注意:
1)上传不同类型的文件需要设置不同的 HTTP Content Header。在文件上传时,Content Header 包含了关于上传内容的类型和其他重要信息,这对于服务器正确解析和处理上传的文件至关重要。一般,cgi程序在main函数开始的位置需要指明Content Header:
cout << "Content-type:text/html;charset=utf-8\r\n\r\n";
当上传.tar.gz类型的压缩包文件时,Content-type:text/html;已不再满足,需要设置tar.gz的Content Header:
HTTPContentHeader("application/x-tar-gz");
2)上传的文件有大小限制。
一般在web server的配置文件中有指定单次POST的数据流大小,若不指明,默认1M。例如:boa web server的boa.conf中修改上限为20M:20*1024*1024 = 20M = 20971520
# SinglePostLimit: The maximum allowable number of bytes in
# a single POST. Default is normally 1MB.SinglePostLimit 20971520
上传文件超过单次请求数据流上限时,报错: