'Saving js dataUrl to file using qml and c++

I'm trying to get a dataUrl object from javascript and convert it to a file by sending it from the website to qml and then to a file.

I have the following code to do this but it doesn't seem to work as intended as the saved file (for example an image) is blank.

In javascript I'm taking the dataUrl and get the base64 part from it.

  async function handleDownload(e) {
    if (link !== null || url != null) {
      e.preventDefault();
      const base64 = url != null ? url.split(',')[1] : link.split(',')[1];
      QML.handleDownload(base64, name);
    }
  }

In qml I have just a simple function that transfers the base64 string to the c++ backend:


function handleDownload(fileBase64, fileName) {
    console.log("Downloaded " + Backend.saveBase64(fileBase64, fileName))
}

And in C++ I'm using the following function to save it to a file'

QString Backend::saveBase64(QString fileBase64, QString fileName) {
    const QByteArray base64Array = fileBase64.toUtf8().toBase64();
    QString path("/home/user/Downloads/" + QString(QDir::separator()) + fileName);
    QFile file(path);
    file.open(QIODevice::WriteOnly);
    file.write(base64Array);
    file.close();
    return path;
}

I want to also add that the dataUrl isn't just an image file but can also be any other file type.



Solution 1:[1]

The question can be also used as an minimal example given that a dataUrl looks something like this: data:[<mediatype>][;base64],<data> and also giving qml and the feature allowing you to communicate between javascript qml and qml cpp.

Anyway. In the end I managed to come up with the following function.


QString Backend::saveBase64(QString fileBase64, QString fileName) {
    QString path("/home/phablet/.cache/cinny.nitanmarcel" + QString(QDir::separator()) + fileName);
    QFile file(path);
    file.open(QIODevice::WriteOnly);
    file.write(QByteArray::fromBase64(fileBase64.toLocal8Bit()));
    file.close();
    return path;
}

What I was doing wrong is that I took the base64 string and converted it again to base64 which resulted in the data being corrupted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexandru Nitan