Angular Image cannot be loaded - html

On the template list of users, I have a column to show the identity image (stored on database) of each user.
On the template file, I have:
<td>
<img src="{{emptyStr.concat(user.pathImage.substr(user.pathImage.indexOf('/assets')))}}" style="max-width:30px"/>
<br/>
{{user.nameImage}}
<br/>
{{emptyStr.concat(user.pathImage.substr(user.pathImage.indexOf('/assets')))}}
</td>
On the component file, emptyStr = "..";
As displayed bellow:
The name and the url of the image are displayed correctly.
However, the image cannot be loaded.
On firefox, there's no error.
However on chrome, I got this error:
Also, I got:
That means that this image doesn't exists on file upload, but no, that exists as displayed by this screenshot.
I think there's a problem of synchronization, because after made some changes on sublime tool, the console ng server will update and both 2 images are shown.
Have you please any idea about solving that issue ?.
Big thanks.

Try this way:
On the template .html:
< img src="{{showImage(user.id)}}" alt="{{showImage(user.id)}}" style="max-width:30px"/>
On the component .ts:
strIntoObjExp: String[] = [];
specialUser: User;
user: User;
showImage(id: number) : String
{
var requesta = new XMLHttpRequest();
requesta.open('GET', 'http://localhost:6227/api/auth/getallfiles', false);
requesta.send(null);
this.strIntoObjExp = JSON.parse(requesta.responseText);
var requestb = new XMLHttpRequest();
requestb.open('GET', 'http://localhost:6227/api/auth/users/' + id, false);
requestb.send(null);
this.specialUser = JSON.parse(requestb.responseText);
this.strIntoObjExp.forEach((exp: String) =>
{
if(exp.includes(this.specialUser.nameImage.substring(0, this.specialUser.nameImage.lastIndexOf("."))))
{
this.imagePath = exp;
}
});
return this.imagePath;
}
HTH

Related

displaying existing images in ngx dropzone

I am using Angular ngx-dropzone to insert images in Mysql and save them on Server. now I need to do preview/edit mode in angular component in the edit mode, I want to show the existing file in the drop box and display the same when uploading drop zone, any ideas? I have the image as a file and its name of it in the database.
You can use the below code for previewing selected images
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
</ngx-dropzone-image-preview>
If you want to show the label also
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
<ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
</ngx-dropzone-image-preview>
I understand your question.I was facing the same issue.For this, you have
to have a blob response. So if you have a url you have to convert it into a
blob response. I have given an example below
URL: string = `https://fireflysemantics.github.io/i/service-parts-
help/electrocardiogram-36732.png`;
files: File[] = [];
this.loadImage().subscribe(i => {
const myFile = new File([i], this.URL, {
type: i.type,
});
this.files.push(myFile)
})
loadImage(): Observable < Blob > {
return this.http.get(this.URL, {
responseType: "blob"
});
}

How to create a string map "location" and "location Value Text" of this string text?

I developed project using anguler with ngRx framework. I used TypeScript with HTML for developing front-end.My db have saved 'HTML' format texts like below.
"<html><body>A.txt
B.txt
D.txt
www.facebook.com
</body></html>"
This text priviouly , I drectly render in html file using <dev INNERHTML ={{stringText }} \> like wise.
But my project using JXBrowser and as it's configuration , this can't be directly open in default browser clicking just link.
For that work ,I need to take href location as URL and when click it passed to .ts file.
I thought ,it change as like this <a role="button" click='getLink(myText)'> {{getLink(value}} </a>'. so ,create this ,I need that text put a array with contain 'location' and value.Next ,I though ,Iterate that array in HTML file.
I need some expert help to do this ? I am struggle with map above text to such kind of string array (eg :array[hrfeLink][value]). Hope some expert help me.
------------Updated---------------
According to the comment, I will try this way, and I can take the link location. But still couldn't take value.
let parser = new DOMParser();
let doc = parser.parseFromString(info, "text/html");
let x = doc.getElementsByTagName('a');
for (let i = 0; i < x.length ; i++) {
console.log(x[i].getAttribute('href'));
}
What is the value that you want? Is it the anchor text of the link?
We create an interface Link with the properties that we want from each link
interface Link {
location: string;
value: string;
}
Then we create a function that extracts all links from an html string and converts them to an array of Link objects.
function parseLinks( stringHTML: string ): Link[] {
// create a parser object
const parser = new DOMParser();
// turn the string into a Document
const doc = parser.parseFromString( stringHTML, "text/html" );
// get all links
const linkNodes = doc.getElementsByTagName('a');
// convert from HTMLCollection to array to use .map()
const linksArray = [...linkNodes];
// map from HTMLAnchorElement to Link object
return linksArray.map( element => ({
location: element.href,
value: element.innerText,
}))
}
Now you can do whatever with the links from your text
const text = `<html><body>A.txt
B.txt
D.txt
www.facebook.com
</body></html>`;
const links: Link[] = parseLinks( text );
// can use like this
links.map( ({location, value}) => {
// do something here
})
Typescript Playground Link

Cannot embed images in email with MailKit

This questions has been posed and answered several places on SO, specifically here : Issue with Gmail - Embedded images using MailKit
and handles my exact query, yet the answer doesn't seem to work for my case.
I've tried to build a simple mailer that embeds images in an HTML email, yet in several clients, all images still end up as attachments.
I suspect the fault to be in the way I handle the image attachments (one .gif and several .png) to be:
// Add pictures to embedded resources and replace links to pictures in the message
foreach (string imgpath in ImgPaths)
{
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
}
builder.HtmlBody = HtmlFormat;
message.Body = builder.ToMessageBody();
I can see from the emails (received in Gmail, for instance), do show that the images are being listed as:
src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei"
All images are attached as attachments in both clients I've tried (gmail and roundcube). I've walked through your tutorials and checked out everything here: https://stackoverflow.com/search?q=Mailkit+Embed
Sadly, I just can't seem to find my error. Hopefully #jstedfast could see where I make my mistake?
UPDATE
As mentioned by #jstedfast, the corrected code should be (for my case anyway):
foreach (string imgpath in ImgPaths)
{
var test = Path.GetFileName(imgpath);
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
//HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
HtmlFormat = HtmlFormat.Replace($"images/{test}", string.Format("cid:{0}", image.ContentId)); //use images/filename
}
This is a great guide to follow too, https://programming.vip/docs/5dac3983f0cd5.html
This looks like the problem:
<img src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
That needs to be:
<img src="cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
My guess is that in order to fix this, you'd change the following line of code:
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
to this:
HtmlFormat = HtmlFormat.Replace(imgpath, string.Format("cid:{0}", image.ContentId));
Hope that helps!

LexResponse output does not understand HTML data

I'm having a problem trying to get my AWS Lambda function to successfully output a series of HTML links when its running a SQL Query.
private string GetEventSearchResults(ILambdaContext context, List<Event> events, string CustomerNumber)
{
var result = string.Empty;
var link = string.Empty;
if (events.Count > 0)
{
result = $"Events for {CustomerNumber}:";
foreach (var evt in events)
{
link = "http://localhost/event/" + $"{evt.ID}";
result += $"<br>Event: {evt.ID} - Status: {evt.Status}";
}
}
else
{
result = "No Data found matching your query";
}
return result;
}
When this method is called by my Lambda function as a LexResponse,
replyMessage = GetEventSearchResults(context, eventList, query.CustomerNumber);
return Close(
sessionAttributes,
"Fulfilled",
new LexResponse.LexMessage
{
ContentType = "PlainText",
Content = replyMessage
}
);
This response is then rendered in my HTML page by a Javascript function. Relevant portion of the Javascript that renders the response:
function showResponse(lexResponse) {
var conversationDiv = document.getElementById('conversation');
var responsePara = document.createElement("P");
responsePara.className = 'lexResponse';
if (lexResponse.message) {
responsePara.appendChild(document.createTextNode(lexResponse.message));
responsePara.appendChild(document.createElement('br'));
}
if (lexResponse.dialogState === 'ReadyForFulfillment') {
responsePara.appendChild(document.createTextNode(
'Ready for fulfillment'));
// TODO: show slot values
}
conversationDiv.appendChild(responsePara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
However, the output shown by the Lex bot is as shown below:
Lex Bot Output
Can anyone please help me understand what exactly is going on? Is the content type of the Lex Response responsible for this? (there's only plaintext and SSML available for Lex Response so I can't change that)
Also, if possible, can anyone please explain how to fix this if at all possible? Thanks!
Your code is correct and output is also correct.
However the console window is not able to render the HTML part of your result.
The client on which you will deploy the chatbot, is responsible for rendering the output. For example, if you respond with a ResponseCard, console or website will not be able to render it correctly but it will be displayed correctly on Facebook and Slack. So, if you integrate your chatbot on some website it will show the links in your output correctly as you desired.
You can try to integrate your chatbot with Slack or Facebook first, to see the rendering of output.
Hope it helps.
After further trial and error, I managed to get a solution that works for me.
function showResponse(lexResponse) {
var conversationDiv = document.getElementById('conversation');
var responsePara = document.createElement("P");
responsePara.className = 'lexResponse';
if (lexResponse.message) {
var message = lexResponse.message.replace(/"/g, '\'');
responsePara.innerHTML = message;
responsePara.appendChild(document.createElement('br'));
}
conversationDiv.appendChild(responsePara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
By making the LexResponse an Inner HTML, it fixed the markup of the text and thus the link can be seen everytime.

Loading local image from Isolated Storage to html page

There's something strange and wired with the "image path" when using it in html page from IsolatedStorage.
I want to create an html-page, that will be used by app's webBrowser object. So I create an html page in IsolatedStorage and then use this page with webBroswser.Navigate.
Everything works fine except the images.
1) If I create an html page and images at the root of IsolatedStorage, everything works fine, the code <img src="image.png"> works and I can see the image at page page.
2) However, the way of saving pages and images at root is not a good idea in my opinion as I already have a number of directories, used by app there, so, I create a new directory "Html" and save all pages there.
Now, when I open this page I can't see my image. I've tried several variations of src links and still can't find an answer.
What'll be the correct link in <img src=..."> tag, if the hierarchy is:
IsolatedStorage-->Html(folder)-->index.html(file)
(1) IsolatedStorage-->Html(folder)-->image.png(file)
(2) IsolatedStorage-->Html(folder)-->Images(folder)-->image.png(file)
Actually, I thought it would be something like <img src="image.png"> for (1), but I tried several similar versions and none of them worked.
Well, that seems a bit strange:
This method will save the picture to the IsolatedStorage, but won't allow to use it in html img tag:
using (IsolatedStorageFile isopicsFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isopicsFile.FileExists(Constants.HtmlFolderName + "launch.png") == false)
{
Stream yourFilepath = Application.GetResourceStream(new Uri("/someUri/launch.png", UriKind.Relative)).Stream;
BitmapImage b = new BitmapImage();
b.SetSource(yourFilepath);
WriteableBitmap wb = new WriteableBitmap(b);
using (var isoFileStream = isopicsFile.CreateFile(Constants.HtmlFolderName + "launch.png"))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
// Theoretically, there may be the problem, as the file extention is png, not jpg
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
And this one will save the picture and will allow to use it with html tags:
string f = "somePath/launch.png";
StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
using (BinaryReader br = new BinaryReader(sr.Stream))
{
byte[] data = br.ReadBytes((int)sr.Stream.Length);
string fileName = "launch.png";
string filePath = Constants.HtmlFolderName + fileName;
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(filePath))
{
isoStore.DeleteFile(filePath);
}
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(filePath)))
{
bw.Write(data);
bw.Close();
}
}
}
Also, in second case, the picture properties must be set to Content + Always Copy.