Access Asset Catalog images in TVML - tvos

I there any way to access images in contained within a local Asset Catalog from within TVML on the AppleTV?
I notice several of the templates in this example from Apple call out to resource:// URLs, which are common use images (more info on the dev forms). Here's an example button that gets rendered with the cloud symbol:
<buttonLockup>
<badge src="resource://button-cloud" class="whiteBadge" />
<title>Title 3</title>
</buttonLockup>
I tried pointing to some of my own resources instead of button-cloud but didn't have any success.
I have been able to change the icon on these buttons by linking to an externally served image like so:
<buttonLockup>
<badge src="http://localhost:5000/static/heartFull.png" class="whiteBadge" width="50" height="50"/>
<title>Title 3</title>
</buttonLockup>
Since these buttons will be re-used throughout my app, I'd rather load them locally than repeatedly calling them over HTTP if possible.

I had some success linking directly to the filesystem
<badge src=\"file:///<url to bundle>/<relative path to resource>/<icon>.png\" width=\"50\" height=\"50\" />
with... url to bundle from NSBundle.mainBundle().bundleURL.absoluteString, relative path according to your setup, eg. resources, images, ... and icon well, your image to show on the badge.
Pulling from Assets.xcassets hasn't worked out so far, but then I am still in training. :-D

I think the icons namespaced with resource are provided by the OS itself and can't be modified. This is only a hunch and I haven't verified it.
https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/ATV_Template_Guide/ResourceValues.html

Thanks #Baa, really helped me out! Just wanted to add that in order to reference the path to the bundle on the JS side, I needed to add the following Swift code to my AppDelegate.swift file within the appController(_ appController: TVApplicationController, evaluateAppJavaScriptIn jsContext: JSContext) function (may need to be manually added, if you don't see it):
jsContext.setObject(Bundle.main.bundleURL.absoluteString, forKeyedSubscript: "BUNDLE_URL" as NSCopying & NSObjectProtocol)
Then on the JS side, I could load static images from the bundle with the following:
const imageFromBundle = `${BUNDLE_URL}myImageName.png`;
Note, as far as I could see, the file:/// prefix was unnecessary and loading bundled images worked fine for me without it.

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().

Serving Polymer App to a /path not at root

So the first thing I want to do with a new Polymer app is deploy to a directory on an existing website. The only thing that seems to work is deploying to root /.
Let's take the Shop example. I do:
polymer init and choose shop
polymer build
Robocopy.exe .\build\bundled\ C:\inetpub\wwwroot\p\ /MIR
start http://localhost/p/
You see I'm on Windows. I assume that using IIS is irrelevant, since I'm relying on the server just to serve static content.
What do I need to edit in the shop template to make it work at the url http://localhost/p/?
The polymer-cli created apps came with assumption of serving from root level '/'. In generated project index.html you will find two comments
<!--
The `<base>` tag below is present to support two advanced deployment options:
1) Differential serving. 2) Serving from a non-root path.
Instead of manually editing the `<base>` tag yourself, you should generally either:
a) Add a `basePath` property to the build configuration in your `polymer.json`.
b) Use the `--base-path` command-line option for `polymer build`.
Note: If you intend to serve from a non-root path, see [polymer-root-path] below.
-->
<base href="/">
<!-- ... -->
<script>
/**
* [polymer-root-path]
*
* By default, we set `Polymer.rootPath` to the server root path (`/`).
* Leave this line unchanged if you intend to serve your app from the root
* path (e.g., with URLs like `my.domain/` and `my.domain/view1`).
*
* If you intend to serve your app from a non-root path (e.g., with URLs
* like `my.domain/my-app/` and `my.domain/my-app/view1`), edit this line
* to indicate the path from which you'll be serving, including leading
* and trailing slashes (e.g., `/my-app/`).
*/
window.Polymer = {rootPath: '/'};
// ...
</script>
if in this index.html file you comment out base tag and set window.Polymer rootPath to something like '/0/polymer-test/build/es5-bundled/' you will be able to navigate in app on http://localhost/0/polymer-test/build/es5-bundled/
The Polymer shop-app assumes it will be deployed on the server root. Therefore it has all of the links and routes hard-coded to that assumption.
This means, that you will have to change all of the following:
all absolute links between the pages,
all pattern parameters in app-route elements (this is not necessary when useHashAsPath = true),
all absolute imports, including the lazy ones via importHref,
update the absolute locations within the service worker (use instructions from here) and
all references to static content (CSS, images, JS files)
I'm guessing your main goal isn't porting the shop-app, but rather future proofing your own app so that it can also be deployed to non-root locations on the server.
For this, I will mention two ways, depending on which value of useHashAsPath you use for the app-location element. This setting defaults to false, which means that you must use full URLs, instead of the hashbang equivalents.
Scenario 1: useHashAsPath = true
This is the easiest of both approaches, since you simply treat all URLs between the pages as absolute links. For example: Tabs.
The next step is to reference all static content and imports via relative links.
The last step is to update your service worker as shown here.
Scenario 2: useHashAsPath = false
If you dislike the hashbang URLs, go for this scenario. As you can figure out, this approach is a bit more difficult, but still manageable (especially when you start from scratch).
Firstly, you should still use absolute links, since relative links between a complex routing scheme can quickly cause problems (e.g. when not all pages are on the same directory level).
But since absolute links are a no-go, you will have to add some additional pre-processing upon build time. The point is to prefix all links with, say __ROOT__, and then replace all of those values with your actual document root. The links would then look like something this:
Some page
And you would use gulp-replace or something similar to replace __ROOT_ with /your-document-root across all of your source files in order to produce something like this:
Some page
At this point, you've got your links fixed. But this is only part of the problem. You must also apply the same fix to all of your app-route elements. For example:
<app-route pattern="__ROOT__/some/page" [...]></app-route> // Other parameters ommited
As with other resources, such as images and CSS files, you can also include them as absolute links and add the __ROOT__ prefix, but I would advise against this and would rather use relative paths.
The last step is to update your service worker as shown here.
Read more about routing: https://www.polymer-project.org/1.0/blog/routing

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I have this problem. Chrome continues to return this error
Resource interpreted as stylesheet but transferred with MIME type text/html
The files affected by this error are just the Style, chosen and jquery-gentleselect (other CSS files that are imported in the index in the same way work well and without error). I've already checked my MIME type and text/css is already on CSS.
Honestly I'd like to start by understanding the problem (a thing that seems I cannot do alone).
i'd like to start by understanding the problem
Browsers make HTTP requests to servers. The server then makes an HTTP response.
Both requests and responses consist of a bunch of headers and a (sometimes optional) body with some content in it.
If there is a body, then one of the headers is the Content-Type which describes what the body is (is it an HTML document? An image? The contents of a form submission? etc).
When you ask for your stylesheet, your server is telling the browser that it is an HTML document (Content-Type: text/html) instead of a stylesheet (Content-Type: text/css).
I've already checked my myme.type and text/css is already on css.
Then something else about your server is making that stylesheet come with the wrong content type.
Use the Net tab of your browser's developer tools to examine the request and the response.
Using Angular?
This is a very important caveat to remember.
The base tag needs to not only be in the head but in the right location.
I had my base tag in the wrong place in the head, it should come before any tags with url requests. Basically placing it as the second tag underneath the title solved it for me.
<base href="/">
I wrote a little post on it here
I also had problem with this error, and came upon a solution. This does not explain why the error occurred, but it seems to fix it in some cases.
Include a forward slash / before the path to the css file, like so:
<link rel="stylesheet" href="/css/bootstrap.min.css">
My issue was simpler than all the answers in this post.
I had to setup IIS to include static content.
Setting the Anonymous Authentication Credentials to Application Pool Identity did the trick for me.
Try this <link rel="stylesheet" type="text/css" href="../##/yourcss.css">
where ## is your folder wherein is your .CSS - file
Don't forget about the: .. (double dots).
I was also facing the same problem. And after doing some R&D, I found that the problem was with the file name. The name of the actual file was "lightgallery.css" but while linking I has typed "lightGallery.css".
More Info:
It worked well on my localhost (OS: Windows 8.1 & Server: Apache).
But when I uploaded my application to a remote server ( Different OS & Web server than than my localhost) it didn't work, giving me the same error as yours.
So, the issue was the case sensitivity (with respect to file names) of the server.
In case you serve static css with nginx you should add
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}
or
location ~ \.css{
default_type text/css;
}
location ~ \.js{
default_type application/x-javascript;
}
to nginx conf
Based on the other answers it seems like this message has a lot of causes, I thought I'd just share my individual solution in case anyone has my exact problem in the future.
Our site loads the CSS files from an AWS Cloudfront distribution, which uses an S3 bucket as the origin. This particular S3 bucket was kept synced to a Linux server running Jenkins. The sync command via s3cmd sets the Content-Type for the S3 object automatically based on what the OS says (presumably based on the file extension). For some reason, in our server, all the types were being set correctly except .css files, which it gave the type text/plain. In S3, when you check the metadata in the properties of a file, you can set the type to whatever you want. Setting it to text/css allowed our site to correctly interpret the files as CSS and load correctly.
#Rob Sedgwick's answer gave me a pointer, However, in my case my app was a Spring Boot Application. So I just added exclusions in my Security Config for the paths to the concerned files...
NOTE - This solution is SpringBoot-based... What you may need to do might differ based on what programming language you are using and/or what framework you are utilizing
However the point to note is;
Essentially the problem can be caused when every request, including
those for static content are being authenticated.
So let's say some paths to my static content which were causing the errors are as follows;
A path called "plugins"
http://localhost:8080/plugins/styles/css/file-1.css
http://localhost:8080/plugins/styles/css/file-2.css
http://localhost:8080/plugins/js/script-file.js
And a path called "pages"
http://localhost:8080/pages/styles/css/style-1.css
http://localhost:8080/pages/styles/css/style-2.css
http://localhost:8080/pages/js/scripts.js
Then I just add the exclusions as follows in my Spring Boot Security Config;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(<comma separated list of other permitted paths>, "/plugins/**", "/pages/**").permitAll()
// other antMatchers can follow here
}
}
Excluding these paths "/plugins/**" and "/pages/**" from authentication made the errors go away.
Cheers!
Using Angular
In my case using ng-href instead of href solved it for me.
Note :
I am working with laravel as back-end
If you are on JSP, this problem can come from your servlet mapping.
if your mapping takes url by defaut like this:
#WebServlet("/")
then the container interpret your css url, and goes to the servlet instead of going to the css file.
i had the same issue, i changed my mapping and now everyting works
i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.
the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.
to counter this you can either use the <base> tag on your html source,
<base href="http://localhost/assets/">
and link to files like,
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>
or use absolute links for all your files.
<link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />
I have a similar problem in MVC4 using forms authentication. The problem was this line in the web.config,
<modules runAllManagedModulesForAllRequests="true">
This means that every request, including those for static content, being authenticated.
Change this line to:
<modules runAllManagedModulesForAllRequests="false">
I also face this problem recently on chrome. I just give absolute path to my CSS file problem solve.
<link rel="stylesheet" href="<?=SS_URL?>arica/style.css" type="text/css" />
For anyone that might be having this issue.
I was building a custom MVC in PHP when I encountered this issue.
I was able to resolve this by setting my assets (css/js/images) files to an absolute path.
Instead of using url like href="css/style.css" which use this entire current url to load it. As an example, if you are in http://example.com/user/5, it will try to load at http://example.com/user/5/css/style.css.
To fix it, you can add a / at the start of your asset's url (i.e. href="/css/style.css"). This will tell the browser to load it from the root of your url. In this example, it will try to load http://example.com/css/style.css.
Hope this comment will help you.
It is because you must have set content type as text/html instead of text/css for your server page (php,node.js etc)
I want to expand on Todd R's point in the OP. In asp.net pages, the web.config file defines permissions needed to access each file or folder in the application. In our case, the folder of CSS files did not allow access for unauthorized users, causing it to fail on the login page before the user was authorized. Changing the required permissions in web.config allowed unauthorized users to access the CSS files and solved this problem.
I have the same exact problem and after a few minutes fooling around I deciphered that I missed to add the file extension to my header. so I changed the following line :
<link uic-remove rel="stylesheet" href="css/bahblahblah">
to
<link uic-remove rel="stylesheet" href="css/bahblahblah.css">
Using React
I came across this error in my react profile app. My app behaved kind of like it was trying to reference a url that doesn't exist. I believe this has something to do with how webpack behaves.
If you are linking files in your public folder you must remember to use %PUBLIC_URL% before the resource like this:
<link type="text/css" rel="stylesheet" href="%PUBLIC_URL%/bootstrap.min.css" />
In case anyone comes to this post and has a similar issue. I just experienced a similar problem, but the solution was quite simple.
A developer had mistakenly dropped a copy of the web.config into the CSS directory. Once deleted, all errors were resolved and the page properly displayed.
I came across the same issue whilst resuming work on a old MEAN stack project. I was using nodemon as my local development server and got the same error Resource interpreted as stylesheet but transferred with MIME type text/html. I changed from nodemon to http-server which can be found here. It immediately worked for me.
This occurred when I removed the protocol from the css link for a css stylesheet served by a google CDN.
This gives no error:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Architects+Daughter">
But this gives the error Resource interpreted as Stylesheet but transferred with MIME type text/html :
<link rel="stylesheet" href="fonts.googleapis.com/css?family=Architects+Daughter">
I was facing similar issue. And Exploring solutions in this fantastic Stack Overflow page.
user54861 's response (mismatching names in case sensetivity) makes me curious to inspect my code again and realized that "I didnt upload two js files that I loaded them in head tag". :-)
When I uploaded them the issue runs away ! And code runs and page rendered without any another error!
So, moral of the story is don't forget to make sure that all of your js files are uploaded where the page is looking for them.
I came across the same issue with a .NET application, a CMS open-source called MojoPortal. In one of my themes and skin for a particular site, when browsing or testing it would grind and slow down like it was choking.
My issue was not of the "type" attribute for the CSS but it was "that other thing". My exact change was in the Web.Config. I changed all the values to FALSE for MinifyCSS, CacheCssOnserver, and CacheCSSinBrowser.
Once that was set the web site was speedy once again in production.
Had the same error because I forgot to send a correct header a first
header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';
I encountered this problem when loading CSS for a React layout module that I installed with npm. You have to import two .css files to get this module running, so I initially imported them like this:
#import "../../../../node_modules/react-grid-layout/css/styles.css";
but found out that the file extension has to be dropped, so this worked:
#import "../../../../node_modules/react-grid-layout/css/styles";
If nodejs and using express
the below code works...
res.set('Content-Type', 'text/css');
I started to get the issue today only on chrome and not safari for the same project/url for my goormide container (node.js)
After trying several suggestions above which didn't appear to work and backtracking on some code changes I made from yesterday to today which also made no difference I ended up in the chrome settings clicking:
1.Settings;
2.scroll down to bottom, select: "Advanced";
3.scroll down to bottom, select: "Restore settings to their original defaults";
That appears to have fixed the problem as I no longer get the warning/error in the console and the page displays as it should. Reading the posts above it appears the issue can occur from any number of sources so the settings reset is a potential generic fix.
Cheers
If you are serving the app in prod make sure you are serving the static files with service worker. I had this error when I was serving only static subfolder of React build on Django (without assets that have styles)

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

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().