Select local files in a Qt HTML5 application using QFileDialog from a QWebView

In a product I’m currently developing, Joined-up Data, I came accross a problem with getting a file path from the user. “But that’s the easiest thing in the world, Martin” I hear you cry. Well, I ‘d normally agree, but what about if you’re trying to do it using the file input field on an HTML page?

ManipuData is built using a Qt HTML5 application which means all of the user interface is written in HTML. The file input field in HTML is meant for sending files to the server from a browser. Yes, the filename is sent along with the file data but not the original path of the file. This is obvious when you think about it as there’s very little chance of the original file path being valid on the server. Also, the specs (W3C and RFC) don’t say anything about the full path being sent, just the file name.

Since I’m hosting this HTML in an application that I’m writing, can’t I just hook up some Javascript and get the file path that way? Well, that was the first thing I tried:

Which resulted in the following alert when I selected a file:


Although the text in the field seems to show the path, when you try to get it in Javascript the path the file is in is apparently C:\fakepath. This obviously isn’t going to do it.

I then started to think about the original problem – getting a file path from the user is easy in Qt, there’s the QFileDialog that does all the work for you. If only I coudl hook that up in a web page….. hang on….. maybe I can!

Enter ‘The Qt WebKit Bridge

In case you don’t know it, this little beauty provides integration between script and HTML with your native Qt app. All you need to do is hook up a QObject derived class with the Javacript of your QWebFrame and Robert is your mother’s brother. Here’s how I did id:

First off, create a QObject derived class to show the QFileDialog, I called mine WebFileDialog:

Then, add our new WebFileDialog class to the Javascript engine for the main frame of the QWebView:

Finally, link  a ‘Browse’ button and the field we want to write the file path to on the HTML page to our WebFileDialog class:


To add a bit more context about this HTML, what I’ve done is this:

  1. Added a simple <button> to trigger the display of the QFileDialog
  2. Added a <span> to show the file path once a file has been selected
  3. Hooked these up to WebFileDialog in the Javascript when the page loads
  4. Added an alert() to show the file path when the selected file is changed (after the QFileDialog has been shown)

As you can see in the screen shot below, we now have the path available to us:


, ,

No comments yet.

Leave a Reply

Powered by WordPress. Designed by Woo Themes