如何在CefSharp中读取上传的文件?

时间:2015-07-06 16:21:19

标签: c# chromium-embedded cefsharp

用户根据 CefSharp 使用我的浏览器。他使用XMLHttpRequest(用于AJAX请求的JavaScript对象)将文件(在文件输入HTML控件中选择)上传到已知服务器。我想拦截并在浏览器中阅读上传文件。

我在浏览器中使用IResourceInterceptor基于 Awesomium 执行相同操作。这很简单,因为ResourceRequest参数包含文件的完整本地路径。如何在 CefSharp 浏览器中执行相同操作?

用户如何使用XMLHttpRequest(JavaScript)上传文件:

var file = document.getElementById('fileInput').files[0];
var formData = new FormData();
formData.append('file', file);

var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';

xhr.open('POST', '/upload', true);
xhr.send(formData);

截取用户文件(C#)的Awesomium方式:

class MyResourceInterceptor : IResourceInterceptor
{
    public ResourceResponse OnRequest(ResourceRequest request)
    {
        // intercept URL with /upload path only
        if (request.Url.AbsolutePath != "/upload")
        {
            return null;
        }

        // full local path for user's file
        var filePath = request[1].FilePath;

        // now I can read and process the file
    }

    public bool OnFilterNavigation(NavigationRequest request)
    {
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

CefSharp目前没有公开访问Post Data的方法,这正是我猜你需要的。

我已经实现了一个包含基本实现的PR,随时可以测试它。见https://github.com/cefsharp/CefSharp/pull/1113

您拥有的另一个选项是实现OnFileDialog,您必须显示自己的对话框,尽管很简单。 https://github.com/cefsharp/CefSharp/blob/cefsharp/41/CefSharp/IDialogHandler.cs#L38