angular2如何渲染服务端返回的二进制流图片

环境:

微服务请求后端,返回二进制流文件(图片) application/octet-stream,在ng2/ng4前端进行展示。

遇到情况:

1.尝试使用URL.createObjectURL(response)后添加 bypassSecurityTrustUrl。依旧提示unsafe

//html
<img [src]="imgUrl">

//ts
getImg() {
        const host = 'http://localhost:8083/';
        const url2 = host + 'api/bpm-extend/repository/process-definitions/myEclipseDemo:7:227504/diagram-resource';
        let firstheaders = new Headers();
        firstheaders.append('Content-Type', 'image/png');
        const opts: RequestOptionsArgs = {
            headers: firstheaders,
            responseType: 3
        }
        this.http.get(url2, opts).map((resp) => resp.json()).catch((err) => {throw err;})
            .subscribe((val) => {
                this.imgUrl = this.sanitizer.bypassSecurityTrustUrl( window.URL.createObjectURL(val) );
        })
    }

问题:

  1. 请问如何解决此情况?

  2. 或者是的方法错了,那有没有其他解决方案?

阅读 6k
3 个回答

自己已解决,感谢关注。

getImg(id: string) {
        const host = '';
        const url2 = host + `server-bpm/api/bpm-extend/repository/process-definitions/${id}/diagram-resource`;
        const firstheaders = new Headers();
        firstheaders.append('Content-Type', 'image/png');
        const opts: RequestOptionsArgs = {
            headers: firstheaders,
            responseType: 3
        };
        this.http.get(url2, opts).map((resp) => resp.json()).catch((err) => {console.log(err); throw err; })
            .subscribe((val) => {
                this.imgUrl = this.sanitizer.bypassSecurityTrustUrl( window.URL.createObjectURL(val) );
        });
    }

function getValidCode(config) {

        var xhr = new XMLHttpRequest();

        xhr.open("post", config.url, true);

        xhr.responseType = "blob";
        xhr.onreadystatechange = function () {
            if (this.status == 200) {
                var blob = this.response,
                    img = document.createElement("img");

                img.alt = '***';
                try {
                    img.onload = function (e) {
                        window.URL.revokeObjectURL(img.src);
                    };
                    img.src = window.URL.createObjectURL(blob);
                } catch (e) {
                    console.log('***');
                }

                if (config.wrap) {
                    angular.element('#' + config.wrap).html(img) || $('#' + config.wrap).html(img);
                } else if (config.fn && typeof config.fn === 'function') {
                    config.fn.call(null, img);
                }
            }
        };
        xhr.send();
    };
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题