【问题标题】:How can I start a download from c++ code compiled web assembly?如何从 c++ 代码编译的 Web 程序集开始下载?
【发布时间】:2023-03-30 02:10:01
【问题描述】:

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

这是 emscripten 代码 sn-p,但它似乎是某种本地文件。

#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-chrome webassembly


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 2011-08-05
      • 1970-01-01
      • 2011-09-08
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      相关资源
      最近更新 更多