首页 > 解决方案 > 如何下载来自 sapui5 中的 odata 服务的 json 文件?

问题描述

我需要通过按下SAPUI5中的按钮从OData 服务下载 JSON 文件。例如,路径是“/abcd()”,文件是 base 64 编码的 JSON。如果有人能让我知道如何使用它并将其下载为纯文本/JSON 格式,我将不胜感激。提前致谢。请帮忙。

我正在尝试这样做:

对于 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) => {
                const blob = new Blob([res], { type: "application/json" });
                if (window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveBlob(blob, "filename");
                } else {
                    const ele = window.document.createElement("a");
                    ele.href = window.URL.createObjectURL(blob);
                    ele.download = "filename";
                    document.body.appendChild(ele);
                    ele.click();
                    document.body.removeChild(ele);
                }
            });
       }

标签: javascriptjquerysapui5

解决方案


我已经解决了这个问题。

onDataDownload: function () {
            //call the function
            let obj = model.getInstance().getModelService().bindContext("/abcd(...)", undefined, {
                $$updateGroupId: "anyName"
            });

            obj.execute("anyName").then(function () {
                var encoded = obj.getBoundContext().getObject().value;
                var decoded = atob(encoded);
                const blob = new Blob([decoded], { type: "application/json" });

                if (window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveBlob(blob, "ABCD.json");
                    
                } else {
                    const ele = window.document.createElement("a");
                    ele.href = window.URL.createObjectURL(blob);
                    ele.download = "ABCD.json";
                    document.body.appendChild(ele);
                    ele.click();
                    document.body.removeChild(ele);
                    
                }
    
            });
            model.getInstance().getModelService().submitBatch("anyName");
        }

推荐阅读