Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Img src path with header params to pass

I have an img tag in jsp page where the src path requires header parameters to pass to get the image. How can we achieve it?

like image 692
Arjun Avatar asked May 12 '14 13:05

Arjun


People also ask

What does img src => do?

The <img> src attribute is used to specify the URL of the source image. Syntax: <img src="URL"> Attribute Values: It contains single value URL which specifies the link of source image. There are two types of URL link which are listed below: Absolute URL: It points to another webpage.

Which attribute is given to give the path of an image to IMG tag?

The src attribute is required, and contains the path to the image you want to embed.

What is an src path?

The source path specifies the directories where the C and C++ source files are located. If you are debugging a user-mode process on the computer where the executable file was built, and if the source files are still in their original location, the debugger can automatically locate the source files.


3 Answers

You can now use fetch() to add your headers and then load the result into an <img>:

const src = 'https://api.mywebsite.com/profiles/123/avatar';
const options = {
  headers: {
    'Some-Header': '...'
  }
};

fetch(src, options)
.then(res => res.blob())
.then(blob => {
  imgElement.src = URL.createObjectURL(blob);
});
like image 195
flawyte Avatar answered Oct 11 '22 12:10

flawyte


First, you'll need to make an ajax request that sets the headers. Then, you need to use some HTML5 APIs to convert binary data recieved to base64. Finally, set the image src with the data: protocol and your base64 data.

var oReq = new XMLHttpRequest();
oReq.open("GET", "yourpage.jsp", true);
oReq.setRequestHeader("Your-Header-Here", "Value");
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var u8 = new Uint8Array(arrayBuffer);
    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/png"; // or whatever your image mime type is
    document.getElementById("yourimageidhere").src="data:"+mimetype+";base64,"+b64encoded;
  }
};
oReq.send(null);

Sources:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

How to convert uint8 Array to base64 Encoded String?

like image 40
DankMemes Avatar answered Oct 11 '22 12:10

DankMemes


You can't access to the header params with the img tag, you've got two solutions :

Use an Ajax request with the header param and load the image data

<img src="data:image/png;base64,[CODE-OF-THE-IMAHE]">

Use GET parameters with a token to replace the header for this functionality

<img src="controller?token=[TOKEN]">

like image 44
Val Entin Avatar answered Oct 11 '22 13:10

Val Entin