当前位置: 首页 > 面试题库 >

使用浏览器中的JavaScript将二进制数据保存为文件

唐博文
2023-03-14
问题内容

我正在使用编写业务应用程序angularJSbyte[]现在,我需要向我返回一个服务方法(包括PDF文件内容),我需要使用将该文件下载PDF到客户端计算机JavaScript

使用HTML5 Apis或任何JavaScript API怎么可能?

我用过了 window.atob(base64String)

JVBERi0xLjMNJeLjz9MNJVBERi1Xcml0ZXIuTkVUIGRiQXV0b1RyYWNrIEx0ZC4NMSAwIG9iag08PA0vVGl0bGUgKEludm9pY2UpDS9BdXRob3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0b3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0aW9uRGF0ZSAoRDoyMDE0MDUwNDE1MDQ0MiswNSczMCcpDS9Nb2REYXRlIChEOjIwMTQwNTA0MTUwNDQyKzA1JzMwJykNPj4NZW5kb2JqDTIgMCBvYmoNWy9QREYgL1RleHQgL0ltYWdlQ10NZW5kb2JqDTMgMCBvYmoNPDwNL1R5cGUgL1BhZ2VzDS9LaWRzIFsgNCAwIFIgNiAwIFIgXQ0vQ291bnQgMg0+Pg1lbmRvYmoNNCAwIG9iag08PA0vVHlwZSAvUGFnZSANL1BhcmVudCAzIDAgUiANL01lZGlhQm94IFsgMCAwIDU5NSA4NDIgXSANL1JvdGF0ZSAwDS9Db250ZW50cyA1IDAgUiANL1Jlc291cmNlcyA8PA0vUHJvY1NldFsvUERGL1RleHQvSW1hZ2VDXQ0vRm9udCA8PCANL0YwIDggMCBSIA0vRjEgMTAgMCBSIA0+Pg0+Pg0+Pg1lbmRvYmoNNSAwIG9iag08PCAvTGVuZ3RoIDEyOTkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4Nc3RyZWFtDQp4nJVZTW/jNhC9+1cQ6KU9rEJKpETllk02LdC0+bCLXAIUqq0kahxpK8vJ5t+XlCxpyKEoJw6CxczjzPO8ITngnlxSElGyeiQLSvSnflp8XS1CQUkiQ7LaLH6+v777n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CRDk4OEM1Q0Q+PEMxRDEwRTQ5ODk0NkJFNEVCRTg1M0VDQkQ5ODhDNUNEPl0NPj4Nc3RhcnR4cmVmDTUwMjMNJSVFT0YN

但是出现以下错误 Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.


问题答案:

如果浏览器支持download锚元素中的属性,则可能发生这种情况。

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


 类似资料:
  • 我正在尝试用JavaScript下载xlsx电子表格。我已经测试了base64数据。我是这样解码的: null

  • 问题内容: HTML5使您可以在本地存储数据,我认为这很好。例如,这是如何使用它: 在html中,您可以通过将图片的源设置为以下内容来动态显示图片: 所以我的问题是 如何将二进制数据转换为base64字符串,以便可以利用html5本地存储? 例如,如果我可以: 我知道我可以通过使用html5将图像包装在画布上并将其转换为base64string来解决此问题。我也可以在服务器上进行特定的服务,该服务

  • 问题内容: 我有一种将数据写入MySQL数据库的表单。我希望用户能够在最终提交后以格式下载数据。 我的代码当前正在将数据库的内容转储到浏览器中,即正在将其写入页面,而不是csv文件。我想将它们发送到链接,并可以选择下载文件。 这是我当前的代码: 当前结果是一个页面,其中包含表中所有数据的转储。没有在所需位置创建文件。我要去哪里错了? 问题答案: 客户端不知道这是CSV文件(毕竟只是文本!)。 尝试

  • 我的项目是一个web应用程序。 目前,它有一种生成文本文件并将其发送到客户端浏览器下载的方法。 我需要修改它,以强制浏览器将文件保存在客户端计算机上的自定义(预定义)位置。

  • 问题内容: 我将Selenium与Python Chrome webdriver一起使用。在我的代码中,我使用了: 将webdriver指向webdriver可执行文件。是否可以将webdriver指向Chrome浏览器二进制文件? 在https://sites.google.com/a/chromium.org/chromedriver/capabilities中,它们具有以下内容(我认为这是我

  • 问题内容: 我正在阅读有关Cookie和其他相关客户端存储选项的信息,并阅读了有关将window.name用作各种数据缓存的信息: http://en.wikipedia.org/wiki/HTTP_cookie#window.name 尽管它确实具有使它不那么令人满意的东西-并且我不会加糖,但从最真实的意义上来说,它绝对是一个hack- 它看起来很有希望。我需要存储约10K的JSON作为客户端缓