Search code examples
c++qtgmailbase64qfile

Write Base64 string in QString as binary file (QFile)


So I have an issue with downloading attachments from gmail api. The code is basically smth like that:

QJsonDocument doc;

QUrl url("https://www.googleapis.com/gmail/v1/users/me/messages/12d144feec288dae/attachments/ANGjdJ8ZGywUR2NG7G0rIXH-mVGNHcFRnjlbz71ZtyUM3zn-sZtPHXVE5T5TqwzkFHovu7mB2zA2wqjIHNA8ysiUPmPbrVoKveuWJjaLFXky0STyESh4uxOOz2933W4uMI6PsynBHS4cpVNMBvSa");
QNetworkRequest request;
request.setRawHeader("Authorization", "Bearer" + myToken);
request.setUrl(url);

QNetworkAccessManager manager;

QNetworkReply *reply = manager.get(request);
QEventLoop wait;

QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &wait, SLOT(quit()));

QTimer::singleShot(5000, &wait, SLOT(quit()));
wait.exec();
doc = QJsonDocument::fromJson(reply->readAll());


//this is working wrong
QString str = doc.object().value("data").toString();
QByteArray arr;
arr.append(str);
QByteArray b64 = QByteArray::fromBase64(arr);
QByteArray fb64 = arr.toBase64();
QFile f("Math.rar");
f.open(QIODevice::WriteOnly);
f.write(b64);
f.close();

I know its not the best code, but i just want to get how to properly save file from Base64. Can anyone help?


Solution

  • I solved the problem. the deal was to add QByteArray::Base64UrlEncoding in function QByteArray::fromBase64. So, the example will be like that:

    QString str = doc.object().value("data").toString(); //getting a binary data from Json
    QByteArray arr;
    arr.append(str);
    QByteArray b64 = QByteArray::fromBase64(arr, QByteArray::Base64UrlEncoding);
    QFile f("Math.rar");
    f.open(QIODevice::WriteOnly);
    f.write(b64);
    f.close();