首页 > 解决方案 > 如何从 c++ 代码编译的 Web 程序集开始下载?

问题描述

我一直在尝试不做这个 javascript 方面,但我还没有找到任何令人满意的东西。Fetch API 似乎是一个很好的线索,但我似乎找不到在浏览器中开始下载的方法,所以它可以下载一个 zip 文件。

这是 emscripten 代码片段,但它似乎是某种本地文件。

#include <stdio.h>
#include <string.h>
#include <emscripten/fetch.h>

void downloadSucceeded(emscripten_fetch_t *fetch) {
  printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
  // The data is now available at fetch->data[0] through fetch->data[fetch->numBytes-1];
  emscripten_fetch_close(fetch); // Free data associated with the fetch.
}

void downloadFailed(emscripten_fetch_t *fetch) {
  printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch->url, fetch->status);
  emscripten_fetch_close(fetch); // Also free data on failure.
}

int main() {
  emscripten_fetch_attr_t attr;
  emscripten_fetch_attr_init(&attr);
  strcpy(attr.requestMethod, "GET");
  attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
  attr.onsuccess = downloadSucceeded;
  attr.onerror = downloadFailed;
  emscripten_fetch(&attr, "myfile.dat");
}

标签: c++google-chromewebassembly

解决方案


将此添加到您的 cpp 文件中。

EM_JS(void, DownloadUrl, (const char* str),
{
    url = UTF8ToString(str);
    var hiddenIFrameID = 'hiddenDownloader';
    var iframe = document.getElementById(hiddenIFrameID);

    if (iframe === null)
    {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }

    iframe.src = url;
});

以及如何使用它的示例。

void Device::DrawContent()
{
    ImGui::Begin("DW Store");

    if (ImGui::Button("Download"))
    {
        DownloadUrl("https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-5.0.402-macos-x64-installer");
    }

    ImGui::End();
}

推荐阅读