Handle downloads with a WebView
-
Hello,
currently, I am migrating my apps from HTML template to QML with WebView because I need the XMLHttpRequest. Now I want to use a function where some data will be downloaded to the device. I used this in an HTML template which worked beforefunction downloadIcsFile() { var state = document.getElementById("state").value; var year = document.getElementById("year").value; var element1 = document.createElement('a'); element1.setAttribute('href', 'data:text/calendar;charset=utf-8,' + encodeURIComponent(icsContent)); element1.setAttribute('download', "ferien-" + state + "-" + year + ".ics"); element1.style.display = 'none'; document.body.appendChild(element1); element1.click(); document.body.removeChild(element1); }
In my QML app with WebView it does nothing. I've learned that a WebView can't handle downloads by itself. But I did not find any example for documentation on how to do this. So, how can I implement the download function?
Thanks in advance!
-
@schlicki2808 The code might be a bit tangled but I hope it helps: https://gitlab.com/cibersheep/quixe-qml/-/tree/master/qml
-
@cibersheep Thanks, this is a good starting point. I've tried around with SingleDownload and DownloadManager component. As long as the content to download comes from a web url, it works fine, but I have much difficulties with data urls.
E.g.:
This works:element1.setAttribute('href', 'data:;base64,' + btoa("Hello World! What's up with you?"));
This doesn't:
element1.setAttribute('href', 'data:;base64,' + btoa(icsContent));
(I left out the mime types because it didn't make any difference)
The only difference is that icsContent contains a long string with line breaks (\n) but apart from that it will also be converted to base64.
My last idea is to create a web service, post the base64 to it and fetch the result by SingleDownload. That means that such a download requires internet which is not nice in this case.
Is there another trick I can use?
-
So, I finally found a solution. Okay, in my case, the constellation is a bit different: I have a qml app with a WebView. I ended up to trigger the download from HTML/Javascript side and to process the download on qml side. I failed to use the SingleDownload component because it can not handle data-URLs. So I implemented my own solution:
// ... WebContext { id: mainContext onDownloadRequested: { var fileUrl = "/home/phablet/.local/share/schulferien.daniel/Downloads/" + download.downloadFileName; var request = new XMLHttpRequest(); request.open("PUT", fileUrl, false); request.send(decodeURIComponent(download.url.toString().replace("data:text/plain;,", ""))); PopupUtils.open(downloadedMessage); } } WebView { id: mainWebView context: mainContext // ...
The "fileUrl" has to point to the application path + Downloads, otherwise a "device not open" error will occur.
-
-