When trying to load an image as a blob from a server response I ran into the issue that Angular2 (7) is considering the provided url as unsafe. When searching for a solution the widely suggested solution is to use DomSanitizer
to bypass the security.
See example from @Amirreza here, but also in other StackOverflow posts the same solution is suggested.
On the angular documentation page for DomSanitizer
they write the following:
bypassSecurityTrustUrl()
WARNING: calling this method with untrusted user data exposes your application to XSS security risks!
Seems to me that it is not safe to do so, unless you are really really sure that the image source can be trusted!
You should consider that even if the source comes from your own server, it might have been uploaded by a user and it would be possible to exploit such a solution by uploading a malicious image.
It is better and more secure to convert the blob (image) into a data-url (a base64 string) and set that as the src
for your image element.
Data URLs are generally considered safe (MDN):
Encoding data into base64 format
base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.
This solution is also suggested in the blog post here and even in the other answer from @Powkachu, but in that answer the mistake is that the base64 protocol identifier is added double (the FileReader::readAsDataURL
already returns this in the result) and unnecessarily passed to the bypassSecurityTrustUrl
from the sanitizer.
The correct, secure and more simple solution would look like this:
let mySrc;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
// result includes identifier 'data:image/png;base64,' plus the base64 data
mySrc = reader.result;
}
Where blob is a Blob
and mySrc
is a dataUrl (base64 string) that now can be set as image src immediately:
<img [src]="mySrc" />
Here a fiddle in plain Javascript to demonstrate the workings of this solution without Angular.