1. c++ 实现 qt 代码
#include <QtCore> #include <QtNetwork> #include <QGuiApplication> #include <emscripten.h> #include <emscripten/html5.h> #include <emscripten/val.h> #include <emscripten/bind.h> using namespace emscripten; void saveFile(const char *data, size_t length, std::wstring fileNameHint) { // Create file data Blob val Blob = val::global("Blob"); val contentArray = val::array(); val content = val(typed_memory_view(length, data)); contentArray.call<void>("push", content); val type = val::object(); type.set("type","application/octet-stream"); val fileBlob = Blob.new_(contentArray, type); // Create Blob download link val document = val::global("document"); val link = document.call<val>("createElement", std::string("a")); link.set("download", fileNameHint); val window = val::global("window"); val URL = window["URL"]; link.set("href", URL.call<val>("createObjectURL", fileBlob)); link.set("style", "display:none"); // Programatically click link val body = document["body"]; body.call<void>("appendChild", link); link.call<void>("click"); body.call<void>("removeChild", link); } int main(int argc, char **argv) { QGuiApplication app(argc, argv); // for the event loop QUrl url("stand.png"); QNetworkRequest request(url); QNetworkAccessManager manager; QObject::connect(&manager, &QNetworkAccessManager::finished, [](QNetworkReply *reply) { qDebug() << "download finished"; if (reply->error()) { qDebug() << "error" << reply->errorString(); } else { QByteArray payload = reply->readAll(); qDebug() << "size" << payload.size(); QByteArray hash = QCryptographicHash::hash(payload, QCryptographicHash::Sha256); qDebug() << "sha256" << hash.toHex(); saveFile(payload.data(),payload.size(), L"s.png"); } }); qDebug() << "download begin"; manager.get(request); return app.exec(); }
2. 部署到falsk的代码
from flask import Flask, send_from_directory from flask_cors import CORS app = Flask(__name__, static_folder='WebAssembly_Qt_6_6_3_single_threaded-Debug') # 允许特定的域名访问 CORS(app, resources={r"/api/*": {"origins": "http://127.0.0.1:5000"}}) # 路由到 index.html @app.route('/') def serve_index(): return send_from_directory(app.static_folder, 'index.html') # 路由到静态文件 @app.route('/<path:path>') def serve_file(path): return send_from_directory(app.static_folder, path) if __name__ == '__main__': app.run(debug=True)
3. 上边的代码放在和debug目录同级(假如名是a.py)。(最主要的是不把把index.html这里要改一下,不修改也可以和代码中的一致就可以了,这里的好处是不修改qt 里的代码结构,直接就部署了)
4. python a.py
5. 在浏览器中运行:127.0.0.1:5000 这时就会下载文件到浏览器中了。
qt-webassembly 实现服务器上的文件下载到本地(浏览器)
最新推荐文章于 2025-02-24 19:52:33 发布