Cannot display images in HTML component - actionscript-3

I have the following HTML component, trying to display a local image, however it will not show up whether I use <img src="file:/tmp/img.png"> or <img src="/tmp/img.png" />. Any ideas why this doesn't work? Saving the file to a local file and opening it works fine!
var xhtml:XML = <html>
<body>
<img src="file:/tmp/logo.gif" />
</body>
</html>;
myhtml.htmlText = xhtml.toXMLString();
Update:
This works fine, btw, if I save the same xhtml to a file and use webkit to open that file using myhtml.htmlLoader.load(new URLRequest("file:///path/to/html/file")).

Did you check for security sandbox violation?
Also did you try with "tmp/img.png" and "./tmp/img.png"?
Or maybe Air doesn't support xhtml, I'm not sure. Try and remove the slash in the img tag like this:
myhtml.htmlText = "<html><body><img src=\"tmp/logo.gif\"></body></html>";

Did you check for any javascript error in other parts of you webpage? They might be preventing your webpage to open.
Syntax looks OK for embedding image, check it here:
http://www.w3schools.com/htmL/tryit.asp?filename=tryhtml_images2

Related

Angular 9 domSanitazer Not allowed to load resource [duplicate]

It works if the html file is local (on my C drive), but not if the html file is on a server and the image file is local. Why is that?
Any possible workarounds?
It would be a security vulnerability if the client could request local file system files and then use JavaScript to figure out what's in them.
The only way around this is to build an extension in a browser. Firefox extensions and IE extensions can access local resources. Chrome is much more restrictive.
shouldn't you use "file://C:/localfile.jpg" instead of "C:/localfile.jpg"?
Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>
C: is not a recognized URI scheme. Try file://c|/... instead.
Honestly the easiest way was to add file hosting to the server.
Open IIS
Add a Virtual Directory under Default Web Site
virtual path will be what you want to browse to in the browser. So if you choose "serverName/images you will be able to browse to it by going to http://serverName/images
Then add the physical path on the C: drive
Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"
Refresh Default Web Site
And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src
Hope this helps someone
we can use javascript's FileReader() and it's readAsDataURL(fileContent) function to show local drive/folder file.
Bind change event to image then call javascript's showpreview function.
Try this -
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function showpreview(e) {
var reader = new FileReader();
reader.onload = function (e) {
$("#previewImage").attr("src", e.target.result);
}
//Imagepath.files[0] is blob type
reader.readAsDataURL(e.files[0]);
}
</script>
</head>
<body >
<div>
<input type="file" name="fileupload" value="fileupload" id="fileupload" onchange='showpreview(this)'>
</div>
<div>
</div>
<div>
<img width="50%" id="previewImage">
</div>
</body>
</html>
IE 9 : If you want that the user takes a look at image before he posts it to the server :
The user should ADD the website to "trusted Website list".
Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.
if you use Google chrome browser you can use like this
<img src="E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
But if you use Mozila Firefox the you need to add "file " ex.
<img src="file:E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
starts with file:/// and ends with filename should work:
<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
I see two possibilities for what you are trying to do:
You want your webpage, running on a server, to find the file on the computer that you originally designed it?
You want it to fetch it from the pc that is viewing at the page?
Option 1 just doesn't make sense :)
Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.
Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.
If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages" in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg"> and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.
(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)
I have tried a lot of techniques and finally found one in C# side and JS Side.
You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag.
Lets look into the below C# code example.
<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>
C# code
if (File.Exists(filepath)
{
byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
var val = $"data: image/png; base64,{base64ImageRepresentation}";
imgEvid.Attributes.Add("src", val);
}
Hope this will help
background-image: url(${localImage});
If you want to add a file as background to your website locally.
You need to upload the image aswell, then link to the image on the server.
what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

Favicon requested on every route change

I think it's strange that a route change would trigger a request for the favicon.
Is this intended or what is going on here?
I had the same problem and I believe the problem started with the Chrome 49.0.2623.87. I hope it is going to be fixed in the coming updates. For now, I am using the script below, which can be found here.
var favIcon = "favicon.ico";
var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.rel = 'shortcut icon';
newLink.href = 'data:image/png;base64,'+favIcon;
docHead.appendChild(newLink);
It will not stop the favicon requests, so for a short period of time you still will see the default favicon from chrome, but I believe there is not much to be done about that.
I found a solution on Github. Quoting #Doeke:
Try reordering the favicon link tags. For me, putting the 16x16 link before 32x32 fixed this issue. As for why this works... I have no idea.
For me, it meant putting the only favicon <link> on my page right at the top of <head>, after <meta charset>.
Try to serve favicon.ico from your server or add route for that. I was experienced such error when using express catch-all app.get('*') method which redirected all requests to index.html (even for favicon)
Change the <link> tag as mentioned below in Step 6, or follow the comments.
Embedding the icon inline as a Data URL will do the magic!
What is a Data URL?
Data URLs allow content creators to embed small files inline in documents.
STEPS:
Convert favicon image to Data URI from this link: Converter
Upload the .ico file from the public folder.
Next, select output format as: Data URI -- data:content/type;base64
Next change the <link> tag's href with the generated output!
Replace this line(<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />) in public > index.html.
T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PCwYSMIsbMWtqYjim5QkWkrvLZDyCyIxujkzV/hjU5i0eGCw7jnBQCVSI5CKtrSpiCdTCgAXjzxw4GCTDYHcEq+UJTJCKWOqaIlIpNSLOQ5BchlM2VSy2ExkCgKot9xxzjZjrSKbUvLsW3Gtm3b/Ld5aSHoDs6qWc9166DAz1/A7z9p94j9K/IPisRBEXwW+XuRmLQ/v4FfRW4BKS4BSstEpDyACqmsolpcVHOpUioIKBcJr6kFSoqdAoV1EFgvGg00ShM5mqE1t0RFtTRrxzSHJmmlVjTaAqGu0BYIr4Z2c2Y64GcsnaLoQkO77iS2CLrN+e6Bh+GWQBH0iklfPwM8HRSRIQxeisjg073H9uT1QpElEEzgd7EYBkZEMYrBqChGgB6x+B5ImCUwxgOxGb/F2IQoojCIEsXEGBcnxeYBl04uMHWEQO1Zh1AEV+xJ/GFO4ksMmg+ZxD/w07WMPY5lnHYvY5exjNMwYxYw9zLK6zqIMDZSLXXSxK1cUcy25OS0vLU2UiMNxkaaszbS8bdy1YGt7HWY5o1t4vDCf56HSfFpfgEglsX8oMOPc1D+IrEAC/OfvA1laXnlo8tQmuDjyvKSp6Gc3dIsU11VprpWhRuq1pSprlqm6m/r6xu3eHrjmeLGU25trHvaundh2YTPHoXFu7Td9ShtZy+u/uW9wL+8+wWMW6cIGBlis7UXcbbFJtWvB7mQJBbxesiKF4sESD5hzEtUMS/m+DFPgokwvi5/aAfNh1n+QdP2owot6j7bi7qroljVou5936jrDNvROwfD9k60f9h2xf2Pzrj/MQCN69fET0Amdi/E/l+X9lz0Dsdc7S4Pmb0rMJQDOxwUASEGZsoMEKa00yXCIEpZt0+Uwo4nL8VdX4o73xDAJyImTqpuCWERUZBeABmUY3imQeHSAAAAAElFTkSuQmCC"
/>
Now whenever this href is parsed, the DATA URL is loaded, instead of the .ico file. Hence, no new requests will be sent to the server as the data is embedded inline!
Change the favicon request by the following line of code in your index.html page
<link rel="icon" href="data:image/vnd.microsoft.icon;base64,<data>">
here, <data> is the base64 data of your favicon.
refer https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
This trick stops the user’s browser from sending an automatic HTTP request for the favicon.
For me, while using Next 13, replacing
<head> with <Head> (note case) seems to fix the issue.

WkHTMLtoPDF not loading local CSS and images

I've seen multiple questions that are very similar to this one, so I was hesitant at first to post it. But nothing suggested resolved my issue and I can't seem to figure out what's wrong myself.
For a project I made for one client they wanted to ability to convert quotes for their customers (generated using an online form) to PDFs. Simple enough. As the entire project was in PHP, I used the following simple process:
Save the quote as a temporary HTML file
Use WkHTMLtoPDF to convert the HTML file to a PDF
Output this PDF file
Clean up (delete temporary files)
This worked until they changed servers. The new server has a firewall.
At first the PDF conversion step was returning a firewall page saying that the server couldn't make outbound connections. To resolve this I fed the HTML file directly instead of linking to it (/var/www/mysite/temp/18382.html instead of www.example.com/temp/18382.html). This converted the HTML, but the firewall prevented the loading of CSS and images
I can overcome the CSS by simply embedding it directly in the site instead of linking to it (using the <style> tags), but this doesn't work for images
I tried using relative links first. I changed <img src="http://www.example.com/temp/image.jpg" /> to <img src="./image.jpg" />. This didn't work.
Next I tried <img src="file:///var/www/mysite/temp/image.jpg" /> but this didn't work, either
I read around and look through the WkHTMLtoPDF manual and I tried several different command line arguments like --enable-local-file-access, --enable /var/www/mysite/temp/, and --images but nothing seems to fix it
In my case - wkhtmltopdf version 0.12.2.1 (with patched qt) - adding a base tag to the head section with the absolute path made sure images and css did get loaded.
<html>
<head>
...
<base href="http://www.example.com/">
<link href="/assets/css/style.css" rel="stylesheet">
...
</head>
If your are on linux check the ownership of your images. For windows you will find some info on http://code.google.com/p/wkhtmltopdf/wiki/Usage.
I tried different kind of paths to the image:
<img src="file:///var/www/testpdf/flowers.jpg"><br>
<img src="./flowers.jpg"><br>
<img src="flowers.jpg"><br>
<img src="/var/www/testpdf/flowers.jpg"><br>
all images are showed correct. I didn't use any command line arguments
(only wkhtmltopdf /var/www/testpdf/makepdf.html makepdf.pdf)
For Windows you need to use absolute file system paths in your markup. For instance:
<link href='C:\Projects\Hello\Hello.Web\Content\custom\home.css' rel='stylesheet' type='text/css' />
! not http://localhost/Hello.Web/Content/custom/home.css
In order to have them embed, you can insert base64 encoded images like :
<img src="data:image/png;base64,someBase64content"/>
When a browser renders your HTML, it uses a relative path (sometimes with a URL at the beginning of it) like this:
<img src="/static/images/some_picture.png">
<img src="http://www.example.com/static/images/some_picture.png">
But when WkHTMLtoPDF is running on your server, it's interfacing with your local files directly through the filesystem, not through a web server. So for local files, unlike a browser, WkHTMLtoPDF wants the actual filepath:
<img src="/var/www/myapplication/static/images/some_picture.png">
(This worked for me with Python Flask)
on Windows use path: file:///C:/some/dir/some/file.img (notice the tripple /)
It is may be too late :)
BTW, just add this config into your options in last.
options = {'enable-local-file-access': None}
pdfkit.from_string(html, 'filename.pdf', options=options)
After taking in everyone's kind assistance from here and around the net, I discovered something that worked for me - coding in asp.net (c#).
I needed to access the image by url (not file path), as the original source html still needed to be accessed. Through troubleshooting, I discovered these points.
These flags had to be passed in to the command line process:
"-q -n --disable-smart-shrinking --images --page-size A4"
URL still has to be absolute.
Image must be a jpg! I was originally trying to do a gif, to no avail.
I discovered adding "--enable-local-file-access" didn't help, as it requires '\' slashes in the image path instead of '/' slashes, which doesn't help if you also hope to use the source html (in some browsers). Also, if you need to access the local file system, you need to provide an absolute path, as it reads straight from the root and goes from there.
Hope this helps others.
Cheers
-y
I know this is quite old topic, but I've just faced the same issue and maybe it will help to someone.
I tried different approaches, like css background image and using string as base64 encoded data image. Sometimes it helped, sometimes not - no particular rule I could found.
It turned out that upgrading library wkhtmltopdf solved the problem.
I was using version 0.12.0 and upgraded to 0.12.3
What fixed it for me was removing the references to my CSS files. It turned out I had was setting img { max-height: 100%; } in an otherwise-empty div so that was being interpreted as max-height: 0.
So check out your CSS and there might an issue there. This worked:
<div><img src="image.png"/></div>
And running command line in the directory with image.png:
wkhtmltopdf example.html example.pdf
But this does not:
<div><img src="image.png" style = "max-height: 100%; "/></div>
Because the image gets squished to 0 height. Firefox seems to correct this so it wasn't obvious.
This is probably due to SE Linux or firewall rules that prevent you from going out on the internet and back to your own server. You can update your host file to point calls to your domain back to your machine's home address.
make sure you have the latest version of wkhtmltopdf with patched qt.
you can implement a helper that flask jinja uses it to distinguish if the template is for rendering or only generating pdf, or maybe both.
let' say that tmpl_bind is the data object to bind in the template, add a new key tmpl_bind["pdf"] set it True or False.
when using wkhtmltopdf or pdfkit, add enable-local-file-access to options object.
now create a helper function called static_file
def static_file(filename, pdf=False):
# wkhtmltopdf only read absolute path
if pdf:
basedir = os.path.abspath(app.root_path)
return "".join([basedir, "/static/", filename])
else:
return url_for('static', filename = filename)
as we say, wkhtmltopdf for some os only read files when you include their absolute path. Note that you may add or remove parts from the app.root_path, according to your app structure, but this will work in most of cases.
in app configuration add this line after importing static_file function if it is in another file
app.jinja_env.globals['static'] = static_file
finally, in the template import files, images by calling the static_file helper function
<link href="{{ static('css/style.css', pdf) }}" rel="stylesheet" />
<img src="{{ static('assets/images/logo.svg', pdf) }}" class="logo">
For me the problem was resolved by doing two things:
1: In your app/config/config.yml
- Under the knp_snappy
- For the option temporary_folder write ./
- i.e: temporary_folder: ./
2: Now in your html.twig pages remove the asset and write:
From: <link rel="stylesheet" type="text/css" href="{{ asset('css/default_template.css') }}">
To: <link rel="stylesheet" type="text/css" href="css/default_template.css">
And after that, it worked for me.
Hopefully i've helped somebody. Thank you !
To generate your pdf with your images or styles you need to provide the server path as follows:
<img src="https://upload.wikimedia.org/wikipedia/...image.png" />
<link href="http://localhost:8080/css/file.css" media="all" rel="stylesheet" type="text/css" />
Note this second link, it's the local address to your stylesheet, or could be a remote like the first link. The file path didn't work for me, only the server path to the resource.
Ps: In my situation, I am using spring boot in Intellij IDE and I needed to invalidate cache of IDE and not run in debug mode in order to work, otherwise it may be not update things.
URL of images must be absolute not relative.
Check this working example in a twig template:
<img src="{{ absolute_url(asset('images/example.png')) }}"/>
Just spent a few days on getting a Flask/ Blueprint /static file/ css to be read by wkhtmltopdf, so I thought I'd share what I learned.
Win 7, Flask 0.12 on Python 3.4.4, using Pycharm pro, latest pdfkit and wkhtmltopdf.
download the wkhtmltopdf here
install it -mine installed on:
C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
right after you import pdfkit into your flask routes.py script ,insert the lines:
path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
(note the "r" in the first line here !! )
when you use pdfkit in a route, add ",configuration = config" as an argument, eg:
pdfkit.from_string(html_text, output_filename, configuration = config)
this tells pdfkit where to look for wkhtmltopdf. Yes, you need to do this.
NOW in your flask BASE TEMPLATE add , _external = True to your css route, eg:
(this will keep wkhtmltopdf from throwing error cant find css)
NOW (serious bootstrap template juju warning):
go into your flask /external libraries /site-packages /flask_bootstrap /templates /base.html template and:
a. fix CSS link:
<link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
add "http:" so it looks like:
<link href="http:{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
b. fix JS links:
add "http:" so the JS links look like:
<script src="http:{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
<script src="http:{{bootstrap_find_resource('js/bootstrap.js', cdn='bootstrap')}}"></script>
and with all this
your flask html to pdf conversion
using pdfkit and wkhtmltopdf
should run without errors.
note: I moved to flask from PHP and if you are a flask-er, please post your solutions up here. The flask community is MUCH smaller than the PHP community so we all have to pitch in.
opt = dict()
opt["orientation"] = "landscape"
opt["enable-local-file-access"] = ""
config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
enable local file access to access images

Enable HTML5 AppCache using javascript?

<html manifest="example.appcache">
Can you add the manifest="example.appcache" part using javascript?
No you can't because the html file is already sent to the server so further changes to manifest attribute won't make the browser react to it.
I tried it with :
document.documentElement.manifest = "site.manifest";
And loading the pages with and without internet, in the seconde case it says "connection error" obviously

Why can't I do <img src="C:/localfile.jpg">?

It works if the html file is local (on my C drive), but not if the html file is on a server and the image file is local. Why is that?
Any possible workarounds?
It would be a security vulnerability if the client could request local file system files and then use JavaScript to figure out what's in them.
The only way around this is to build an extension in a browser. Firefox extensions and IE extensions can access local resources. Chrome is much more restrictive.
shouldn't you use "file://C:/localfile.jpg" instead of "C:/localfile.jpg"?
Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>
C: is not a recognized URI scheme. Try file://c|/... instead.
Honestly the easiest way was to add file hosting to the server.
Open IIS
Add a Virtual Directory under Default Web Site
virtual path will be what you want to browse to in the browser. So if you choose "serverName/images you will be able to browse to it by going to http://serverName/images
Then add the physical path on the C: drive
Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"
Refresh Default Web Site
And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src
Hope this helps someone
we can use javascript's FileReader() and it's readAsDataURL(fileContent) function to show local drive/folder file.
Bind change event to image then call javascript's showpreview function.
Try this -
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function showpreview(e) {
var reader = new FileReader();
reader.onload = function (e) {
$("#previewImage").attr("src", e.target.result);
}
//Imagepath.files[0] is blob type
reader.readAsDataURL(e.files[0]);
}
</script>
</head>
<body >
<div>
<input type="file" name="fileupload" value="fileupload" id="fileupload" onchange='showpreview(this)'>
</div>
<div>
</div>
<div>
<img width="50%" id="previewImage">
</div>
</body>
</html>
IE 9 : If you want that the user takes a look at image before he posts it to the server :
The user should ADD the website to "trusted Website list".
Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.
if you use Google chrome browser you can use like this
<img src="E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
But if you use Mozila Firefox the you need to add "file " ex.
<img src="file:E://bulbpro/pic_bulboff.gif" width="150px" height="200px">
starts with file:/// and ends with filename should work:
<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
I see two possibilities for what you are trying to do:
You want your webpage, running on a server, to find the file on the computer that you originally designed it?
You want it to fetch it from the pc that is viewing at the page?
Option 1 just doesn't make sense :)
Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.
Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.
If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages" in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg"> and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.
(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)
I have tried a lot of techniques and finally found one in C# side and JS Side.
You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag.
Lets look into the below C# code example.
<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>
C# code
if (File.Exists(filepath)
{
byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
var val = $"data: image/png; base64,{base64ImageRepresentation}";
imgEvid.Attributes.Add("src", val);
}
Hope this will help
background-image: url(${localImage});
If you want to add a file as background to your website locally.
You need to upload the image aswell, then link to the image on the server.
what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().