Search code examples
c#chromium-embeddedcefsharp

How can I read uploaded file in CefSharp?


User uses my browser based on CefSharp. He uploads a file (which is selected in file input HTML control) to known server using XMLHttpRequest (it's JavaScript object for AJAX requests). I want to intercept and to read the uploading file in my browser.

I do the same in my browser based on Awesomium using IResourceInterceptor. It's easy, because ResourceRequest parameter contains full local path of the file. How can I do the same in CefSharp browser?

How user uploads file using 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);

Awesomium way to intercept user's file (C#):

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;
    }
}

Solution

  • CefSharp doesn't currently expose a way to access Post Data which is what I'm guessing you require.

    I have implemented a PR that contains a basic implementation, feel free to test it out. See https://github.com/cefsharp/CefSharp/pull/1113

    The other option you have is implement OnFileDialog, you'd have to display your own dialog, simple enough though. https://github.com/cefsharp/CefSharp/blob/cefsharp/41/CefSharp/IDialogHandler.cs#L38