简体   繁体   中英

How to use XMLHttpRequest with Open Layers

I need to get images from multiple WebMapServers (of my company) with Open Layers (and pure Javascript). Basically it works. Problem is that some servers require HTTP Basic Auth. The OL documentation and a related SO question say that this should be done with a XMLHttpRequest inside an imageLoadFunction:

https://openlayers.org/en/latest/apidoc/module-ol_Image.html

How to assign basic authentication header to XMLHTTPREQUEST?

At first I want to get images with XMLHttpRequest and without Basic Auth:

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Image({
            source: new ol.source.ImageWMS({
                ratio: 1,
                params: { LAYERS: 'ENC', CSBOOL: '2083', CSVALUE: ',,,,,3'},
                url: 'https://wms-without-basic-auth.com/?',
                imageLoadFunction: function(image, src) {
                    image.getImage().src = src;
                    /*
                    var client = new XMLHttpRequest();
                    client.open('GET', src, true);
                    client.setRequestHeader( 'Content-Type',   'image/png' );
                    client.setRequestHeader( 'Accept', 'image/png' );
                    client.onload(function() {
                        image.getImage().src = src;
                    });
                    client.send();
                    */
                },
            })
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([6,54]),
        zoom: 6
    })
});

The imageLoadFunction only works with the line

image.getImage().src = src;

but not with the commented XMLHttpRequest. I think the loaded image must be assigned in the client.onload function, but I'm not sure how to do this. So how should I use the XMLHttpRequest inside the imageLoadFunction?

From the docs :

Providing a custom imageLoadFunction can be useful to load images with post requests or - in general - through XHR requests, where the src of the image element would be set to a data URI when the content is loaded.

Maybe try something like this:

imageLoadFunction: function(image, src) {
  var client = new XMLHttpRequest();
  client.open('GET', src, true);
  client.setRequestHeader( 'Content-Type',   'image/png' );
  client.setRequestHeader( 'Accept', 'image/png' );
  client.responseType = 'blob';
  client.onload(function() {
    const blob = new Blob(client.response);
    const urlData = URL.createObjectURL(blob);
    image.getImage().src = urlData;
  });
  client.send();
},

What it does:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM