最近需要做一个QT上位机,在里面搭建一个小的WEB服务器,主要是用于wget下载升级使用。
查询了各种资料,最终选择了QtWebApp。这个框架对我来说足够用了。
搭建的过程主要参考了QtWebApp的使用
这个文章讲的非常清楚。
下面是重点
由于我主要是用来下载升级使用,所以文件下载功能是重点。但在调试的时候,发现服务器只能下载单个文件,无法下载文件夹。
QtWebApp的源代码如下:
// If the filename is a directory, append index.html.
if (QFileInfo(docroot+path).isDir())
{
path+="/index.html";
}
意思就是当服务器检测到客户端要下载文件夹时,会发送一个index.html出去。这是什么鬼???
后面经过我反复查找资料,才发现这个index.html里面是包含着文件夹里面的内容信息的。就是说文件夹里面有什么东西,在这个index.html里面都有体现。客户端根据这个index.html逐个下载里面的文件,最终达到下载整个文件夹的目的。
ps:以上都是我个人的小小猜测,有大佬看到后欢迎给小白解下惑,嘿嘿。
原理都弄清楚了,代码就知道怎么写了。
修改后的代码如下:
// If the filename is a directory, append index.html.
if (QFileInfo(docroot+path).isDir())
{
QString current_path = docroot+path;//当前路径
QDir dir(current_path);
QStringList dir_list;
QStringList file_list;
if (!dir.exists()) //判断目录是否存在
{
return;
}
//拿到路径下所有文件夹和文件,并且去掉"."和"..",下面两个函数不能打断点,否则debug时可能出错
//QFileInfoList info_list = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
//QStringList namelist = dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
dir_list = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
file_list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
QFile file(current_path+"/index.html");//当前路径下的index.html
file.open(QIODevice::ReadWrite|QFile::Truncate);//打开并清空文件
//写文件,组包
QString index_date;
index_date.append("<html>\r\n<head><title>Index of ");
index_date.append(path);
index_date.append("</title></head>\r\n");
index_date.append("<body>\r\n");
index_date.append("<h1>Index of ");
index_date.append(path);
index_date.append("</h1><hr><pre><a href=\"../\">../</a>\r\n");
for(int i=0; i<dir_list.count(); i++)
{
index_date.append("<a href=\"");
index_date.append(dir_list[i]);
index_date.append("/\">a/</a>\r\n");
}
for(int i=0; i<file_list.count(); i++)
{
index_date.append("<a href=\"");
index_date.append(file_list[i]);
index_date.append("\">a/</a>\r\n");
}
index_date.append("</pre><hr></body>\r\n");
index_date.append("</html>\r\n");
file.write(index_date.toLatin1(),index_date.size());
file.close();
path+="/index.html";
}
代码写的一般般,或许还有些未知的BUG,仅做记录和交流。大佬轻拍。
另外这个代码配合wget食用更佳(其他的客户端没做试验,能不能用未知)。
wget命令如下:
wget http://192.168.6.40:80/files/ -r -c -np -nH --cut-dirs 1 --restrict-file-names=nocontrol
注意上面的数字,这个很重要,需要根据不同的目录深度做相应的调整,如根目录就是0,下一级就是1,再下一级就是2…
小白的理解比较浅显,欢迎大家交流。
以上。
如果觉得这篇文章对您有帮助,欢迎点赞、评论、转发、收藏!您的支持是我创作的最大动力!