Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如果构建一个httpserver用于文件下载 #58

Open
zwallow51 opened this issue Apr 12, 2023 · 4 comments
Open

如果构建一个httpserver用于文件下载 #58

zwallow51 opened this issue Apr 12, 2023 · 4 comments

Comments

@zwallow51
Copy link

编译过了,但是不知道如何添加被能被下载的指定文件

@188080501
Copy link
Owner

目前不能自动搜索和匹配文件,需要手动根据传入的数据匹配对应的文件,然后调用replyFile接口返回

@zwallow51
Copy link
Author

zwallow51 commented Apr 13, 2023 via email

@188080501
Copy link
Owner

188080501 commented Apr 14, 2023

可以参考下这个

void onRequestAccepted(const QPointer< JQHttpServer::Session > &session)
{
    if ( session->requestMethod() != "GET" )
    {
        session->replyText( "unsupport request method", 404 );
        return;
    }

    auto relativeFilePath = session->requestUrlPath();
    if ( relativeFilePath.isEmpty() )
    {
        session->replyText( "path is empty", 404 );
        return;
    }

    if ( relativeFilePath.isEmpty() ||
         relativeFilePath.startsWith( "." ) ||
         !relativeFilePath.startsWith( "/" ) ||
         relativeFilePath.contains( ".." ) ||
         relativeFilePath.contains( "\\" ) ||
         ( relativeFilePath.size() > 1000 ) )
    {
        session->replyText( "path error", 404 );
        return;
    }

    QFileInfo fileIfno( QString( "%1%2" ).arg( webPath_, relativeFilePath ) );

    if ( !fileIfno.exists() )
    {
        session->replyText( "file not exists", 404 );
        return;
    }

    if ( fileIfno.suffix().toLower() == "html" )
    {
        QFile file( fileIfno.filePath() );
        file.open( QIODevice::ReadOnly );

        const auto data = file.readAll();

        session->replyBytes( data, "text/html;charset=UTF-8" );
    }
    else if ( QSet< QString >( { "png", "jpg", "jpeg", "ico", "bmp" } ).contains( fileIfno.suffix().toLower() ) )
    {
        session->replyImage( fileIfno.filePath() );
    }
    else
    {
        session->replyFile( fileIfno.filePath() );
    }
}

@zwallow51
Copy link
Author

zwallow51 commented Apr 15, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants