如何从 C++ 代码编译的 Web 程序集开始下载?

How can I start a download from c++ code compiled web assembly?

我一直在努力不做这 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");
}

将此添加到您的 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();
}