赞助

CEF 文件下载

转载:https://blog.csdn.net/liuyan20092009/article/details/53819473?locationNum=6&fps=1

转载:https://blog.csdn.net/guniwi/article/details/83013415

转载:https://magpcss.org/ceforum/apidocs3/(CEF3较为权威的中文文档)

转载:https://blog.csdn.net/yingwang9/article/details/82187544(cef 本地web资源 打包 加密)

CefClient

CefClient提供访问Browser实例的回调接口。一个CefClient实现可以在任意数量的Browser进程中共享。以下为几个重要的回调:

  • 比如处理Browser的生命周期,右键菜单,对话框,通知显示, 拖曳事件,焦点事件,键盘事件等等。如果没有对某个特定的处理接口进行实现会造成什么影响,请查看cef_client.h文件中相关说明。
  • OnProcessMessageReceived在Browser收到Render进程的消息时被调用。

1.实现CEF在html里面下载文件,首先要让我们自己的CefClient这个类公有继承CefDownloadHandler

    

2.添加下载事件构造函数

virtual CefRefPtr<CefDownloadHandler> GetDownloadHandler() override;  // 声明
CefRefPtr<CefDownloadHandler> CCefClientHandler::GetDownloadHandler() //实现
{
    return this;
}

 

3.然后重写父类的OnBeforeDownload和OnDownloadUpdated两个方法

在.h文件中添加函数声名

virtual void OnBeforeDownload(
        CefRefPtr<CefBrowser> browser,
        CefRefPtr<CefDownloadItem> download_item,
        const CefString& suggested_name,
        CefRefPtr<CefBeforeDownloadCallback> callback)  OVERRIDE;

    virtual void OnDownloadUpdated(
        CefRefPtr<CefBrowser> browser,
        CefRefPtr<CefDownloadItem> download_item,
        CefRefPtr<CefDownloadItemCallback> callback);

在.cpp中重写函数

void CCefBrowserEventHandler::OnBeforeDownload(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefDownloadItem> download_item,
    const CefString& suggested_name,
    CefRefPtr<CefBeforeDownloadCallback> callback)
{

    WCHAR sMyDocuPath[800] = { 0 };
    ::SHGetSpecialFolderPathW(0, sMyDocuPath, CSIDL_PERSONAL, 0);

    wstring sDownloadPath = sMyDocuPath;
    sDownloadPath += L"\\";
    sDownloadPath += suggested_name.ToWString();

    wstring wstrExt = suggested_name.ToWString();
    string::size_type position = wstrExt.find(L".");

    if (position == -1)//没找到,说明文件没有扩展名,我们补上默认文件扩展名,不然下载好的文件无法查看
    {
        sDownloadPath += L".jpg";
    }

    CefString sPath;
    sPath.FromWString(sDownloadPath);
    //Param [download_path] Set |download_path| to the full file path  for the download including the file name
    //Param [show_dialog] Set | show_dialog | to true if you do wish to show the default "Save As" dialog.

    callback->Continue(sDownloadPath, true);//第一个参数是设置文件保存全路径包含文件名
}

void CCefBrowserEventHandler::OnDownloadUpdated(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefDownloadItem> download_item,
    CefRefPtr<CefDownloadItemCallback> callback)
{
    if (download_item->IsComplete())//下载完成
    {
        wstring sFilePath = download_item->GetFullPath().ToWString();//拿到下载完成文件全路径
    }
}

 

posted @ 2018-12-08 16:08  车臣  阅读(4456)  评论(0编辑  收藏  举报