You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SAPUI5中下载OData服务返回的Base64编码JSON文件

SAPUI5 OData Base64 JSON文件下载实现方案

现有实现缺陷

  • 未对接口返回的Base64编码内容做解码处理,直接生成的Blob对应文件为不可读的Base64字符串,无法得到正常JSON内容
  • 未处理Unicode字符解码逻辑,若JSON包含中文等非ASCII字符会出现乱码
  • 未释放生成的临时URL对象,会造成浏览器内存占用冗余

可直接使用的修正代码

XML视图(原有逻辑无需修改)

<form:SimpleForm layout="ResponsiveGridLayout"
            width="30rem"
            editable="true"
            visible="{model>/download}">
            <form:toolbar>
                <Toolbar>
                    <Title id="idTitle"
                        text="{i18n>title}" />
                </Toolbar>
            </form:toolbar>
            <Button id="idDownload"
                text="Download"
                press="onDataDownload" />
        </form:SimpleForm>

JS控制器

onDataDownload: function () {
    return model.getInstance().getOdataWrapper().getEntitySet({
        path: "/abcd"
    }).then((res) => {
        // 请根据实际OData返回结构调整Base64字符串的取值路径,若响应直接返回Base64字符串则无需修改
        const base64Content = res;
        // Base64解码,兼容中文等Unicode字符
        const rawStr = window.atob(base64Content);
        const uint8Arr = new Uint8Array(rawStr.length);
        for (let i = 0; i < rawStr.length; i++) {
            uint8Arr[i] = rawStr.charCodeAt(i);
        }
        const jsonContent = new TextDecoder('utf-8').decode(uint8Arr);
        // 生成JSON文件并触发下载
        const blob = new Blob([jsonContent], { type: "application/json;charset=utf-8" });
        const downloadFileName = "export.json";
        if (window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, downloadFileName);
        } else {
            const tempLink = window.document.createElement("a");
            tempLink.href = window.URL.createObjectURL(blob);
            tempLink.download = downloadFileName;
            document.body.appendChild(tempLink);
            tempLink.click();
            document.body.removeChild(tempLink);
            // 释放临时URL占用的内存
            window.URL.revokeObjectURL(tempLink.href);
        }
    }).catch((error) => {
        // 可自定义添加请求失败的用户提示逻辑
        console.error("文件下载失败:", error);
    });
}

注意事项

  • 若你的OData接口为函数导入类型,返回内容被包装在标准OData响应结构中,请先对应提取Base64字符串的字段,常见取值为res.d.Content、res.results[0].content等,需结合你的实际接口返回结构调整
  • 若需要导出为纯文本格式,仅需修改Blob的type属性为text/plain;charset=utf-8,文件名后缀改为.txt即可

内容的提问来源于stack exchange,提问作者Nandita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:36:03