码迷,mamicode.com
首页 > Web开发 > 详细

Libevent::evhttp服务器下载

时间:2019-01-10 10:47:39      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:cti   att   connect   ESS   \n   utf-8   name   cli   span   

 

void http_handler_Get_Download(struct evhttp_request *req, void *arg)
{
    if (req == NULL)
    {
        return;
    }
    const char *uri = evhttp_request_get_uri(req);
    string strUrl(uri);

    string strFilePath = DPC::get_Url_path(strUrl, "path=");
    printf("FilePath = %s \n", strFilePath.c_str());

    string strFileName = DPC::get_FileName_path(strUrl, "/");
    strFileName = "attachment; filename=" + strFileName;

    //查看文件是否存在
    if (access(strFilePath.c_str(), 0) == -1)
    {
        evhttp_send_error(req, HTTP_BADREQUEST, 0);
        return;
    }
    //=========
    std::ifstream t;
    t.open(strFilePath.c_str(), ios::in | ios::binary);
    t.seekg(0, std::ios::end);
    long length = t.tellg();
    t.seekg(0, std::ios::beg);

    char *buffer = new char[length];
    t.read(buffer, length);
    t.close();

    char FileSize[10] = { \0 };
    snprintf(FileSize, sizeof(FileSize), "%d", length);

    time_t timep;
    time(&timep);
    char s[50];
    sprintf(s, ctime(&timep));
    std::string strDate = std::string(s, s + (strlen(s) - 1));
    evhttp_add_header(evhttp_request_get_output_headers(req), "Server", "Unix");
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/octet-stream; charset=utf-8");
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Disposition", strFileName.c_str());
    evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Length", FileSize);
    evhttp_add_header(evhttp_request_get_output_headers(req), "Date", strDate.c_str());
    evhttp_add_header(evhttp_request_get_output_headers(req), "Connection", "close");
    //=========

    //回响应
    struct evbuffer *retbuff = NULL;
    retbuff = evbuffer_new();
    if (retbuff == NULL)
    {
        return;
    }
    evbuffer_add(retbuff, buffer, length);
    //evbuffer_add_printf(retbuff, "123");
    evhttp_send_reply(req, HTTP_OK, "Client", retbuff);
    evbuffer_free(retbuff);
}

 

Libevent::evhttp服务器下载

标签:cti   att   connect   ESS   \n   utf-8   name   cli   span   

原文地址:https://www.cnblogs.com/osbreak/p/10247991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!