如何从需要基本身份验证的网址获取src

时间:2019-11-07 11:14:38

标签: javascript xmlhttprequest html5-audio basic-authentication

在我们的应用中,我们具有以下HTML代码

<audio controls="controls" src="http://user:password@server:port/searchapi?command=replay&amp;id=9203732824369002191_2"> Your browser does not support the HTML5 Audio element. </audio>

它转到上面的URL,并应该获得音频文件。

但是,并非所有浏览器都支持它,因此我们决定执行以下操作:

  1. 代替该授权执行发送GET请求的JS代码
  2. 在src属性中放置文件本身。

代码如下:

var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'server:port/searchapi?command=replay&amp;id=9203732824369002191_2', false);
myRequest.setRequestHeader('Authorization', 'Basic ' + btoa('user:password'));
myRequest.send();

问题是,如何在呈现页面时在页面上执行它?我的意思是将代码直接放在src标签名称中?

还有,有什么方法可以动态确定mime类型? In the answer是经过硬编码的,并且它们处理图像而不是音频。有区别吗?

我写了以下内容(没有身份验证):

<audio id= "audioElement" controls="controls" [src]="getAudio()"> Your browser does not support the HTML5 Audio element. </audio>

<script>
    function getAudio() 
    {

        var oReq = new XMLHttpRequest();
        oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function (oEvent) 
        {
          var arrayBuffer = oReq.response;
          if (arrayBuffer) {
          var u8 = new Uint8Array(arrayBuffer);
          var b64encoded = btoa(String.fromCharCode.apply(null, u8));
          var mimetype="audio/ogg"; 
          document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
          oReq.send(null);
        }
    }
</script>

但这不起作用。

出什么问题了?

谢谢。

1 个答案:

答案 0 :(得分:0)

好吧,看来实现这种行为的正确方法如下:

<audio id= "audioElement" controls="controls"> Your browser does not support the HTML5 Audio element. </audio>

<script>

    window.onload = function() 
    {
      var oReq = new XMLHttpRequest();
      oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
      oReq.responseType = "arraybuffer";

      oReq.onload = function (oEvent) 
      {
          var arrayBuffer = oReq.response; 
          if (arrayBuffer) 
          {
            var u8 = new Uint8Array(arrayBuffer);
            var b64encoded = btoa(String.fromCharCode.apply(null, u8));
            var mimetype="audio/ogg"; // or whatever mime type is
            document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
          }
      }
      oReq.send(null);
    }

</script>

希望它也可以使用基本身份验证...