Sinatra serving images in HTML - html

So I currently have a very simple Sinatra server. I have a public folder that has css, js, and images as folders within it. In my view when I try to do something like <img src="/images/blah.png">, I get a 404 response. I thought the default of the public folder is public. I feel like I'm not including something or doing something stupid. I am using bootstrap and the css & js files are served fine. It isn't clear to me why I'm getting this 404 with the images?
This is how I'm running my application
#!/usr/bin/env ruby
$: << File.dirname(__FILE__)
require 'load_test_ui.rb'
unless ARGV[0].nil?
class LoadTestUI < Sinatra::Base
set :port, ARGV[0]
end
end
LoadTestUI.run!

It was indeed a stupid mistake; I wasn't URI encoding the source. When I changed the name to just blah.png, it rendered correctly!

Related

Inserting an image from local directory in thymeleaf spring framework (with maven)

I have developed a project using this link: https://spring.io/guides/gs/serving-web-content/ I used maven to develop above project.
I have two html files under this. abc.html and xyz.html. To insert images in the html page, I have used the url like this:
<img src="https://example.com/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px">
But I want to use an image file located in my server instead. I tried placing the file in the same directory of html file but its not working. I even tried giving full path but of no use. This is an ubuntu OS. Please help me out here. Is there any place where I can configure the base path or basically how to put an image from my local folder.
I want you to look into the Thymeleaf's documentation of Standard URL Syntax and specifically the context-relative and server-relative url patterns.
Context-relative URL:
If you want to link resources inside your webapp then you should use
context relative urls. These are URLs which are supposed to be
relative to the web application root once it is installed on the
server. For example, if we deploy a myapp.war file into a Tomcat
server, our application will probably be accessible as
http://localhost:8080/myapp, and myapp will be the context name.
As JB Nizet the following will work for you as I have used thymeleaf personally in a webapp project,
<img th:src="#{/images/test.png}"/>
and the test.png should be under your project root inside the webapp folder. Something navigated through roughly like,
Myapp->webapp->images->test.png
Eg:
<img th:src="#{/resources/images/Picture.png}" />
Output as:
<img src="/resources/image/Picture.png" />
When you hit http://localhost:8080/myapp/resources/images/Picture.png in you browser then you should be able to access the image for the above syntax to work. And your resources folder will probably under webapp folder of your application.
Server-relative URL:
Server-relative URLs are very similar to context-relative URLs, except
they do not assume you want your URL to be linking to a resource
inside your application’s context, and therefore allow you to link to
a different context in the same server
Syntax:
<img th:src="#{~/billing-app/images/Invoice.png}">
Output as:
<a href="/billing-app/showDetails.htm">
The above image will be loaded from an application different from your context and if an application named billing-app is present in your server.
Sourced from: Thymeleaf documentation
You need to understand how HTTP works. When the browser loads a page at URL
http://some.host/myWebApp/foo/bar.html
and the HTML page contains
<img src="images/test.png"/>
the browser will send a second HTTP request to the server to load the image. The URL of the image, since the path is relative, will be http://some.host/myWebApp/foo/images/test.png. Note that the absolute path is composed from the current "directory" of the page, concatenated with the relative path of the image. The path of the server-side JSP or thymeleaf template is completely irrelevant here. What matters is the URL of the page, as displayed in the address bar of the browser. This URL is, in a typical Spring MVC application, the URL of the controller where the initial request was sent.
If the path of the image is absolute:
<img src="/myWebApp/images/test.png"/>
then the browser will send a second request to the URL http://some.host/myWebApp/images/test.png. The browser starts from the root of the web server, and concatenates the absolute path.
To be able to reference an image, whetever the URL of the page is, an absolute path is thus preferrable and easier to use.
In the above example, /myWebAppis the context path of the application, that you typically don't want to hard-code in the path, because it might change. Thankfully, according to the thymeleaf documentation, thymeleaf understands that and provides a syntax for context-relative paths, which thus transforms paths like /images/test.png into /myWebApp/images/test.png. So your image should look like
<img th:src="#{/images/test.png}"/>
(I've never used thymeleaf, but that's what I deduce from the documentation).
And the test.png image should thus be in a folder images located under the root of the webapp.
Get link on Internet:
String src = "https://example.com/image.jpg";
HTML: <img th:src="#{${src}}"/>
I have used bellow like..
My image path is like bellow..
I have used bellow code for loading image
<img th:src="#{imges/photo_male_6.jpg}" >
It is working fine for me.
Recently I had similar issue, but in my case, the spring security was making a problem. As mentioned in other answers and documentation:
<img th:src="#{/img/values.png}" alt="Media Resource"/>
should be enough. But since the spring security has been added to my project, I had to all /img/ ** for get Requests and add addResourceHandlers. Here is the code:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/webjars/**",
"/img/**",
"/css/**",
"/js/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/",
"classpath:/static/img/",
"classpath:/static/css/",
"classpath:/static/js/");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.authorizeRequests().antMatchers(HttpMethod.GET, "/js/**", "/css/**", "/img/**" ,"/pressiplus", "/public/**", "/index", "/", "/login").permitAll();
http.authorizeRequests()
.antMatchers("/secure/admin/**").hasAnyRole("ADMIN","USER")
.antMatchers("/secure/admin/**").hasAnyRole("ADMIN")
.and()
.formLogin() //login configuration
.loginPage("/login")
.failureUrl("/login-error")
.loginProcessingUrl("/login")
.usernameParameter("email")
.passwordParameter("password")
.successHandler(myAuthenticationSuccessHandler())
.and()
.logout() //logout configuration
.logoutUrl("/logout")
.logoutSuccessHandler(myLogoutSuccessHandler)
.and()
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(7 * 24 * 60 * 60) // expires in 7 days
.and()
.exceptionHandling() //exception handling configuration
.accessDeniedHandler(accessDeniedHandler());
}
}
I hope this helps someone in the future
Who retrieve link dynamically use this pattern
<img class="image" th:src="#{'/resources/images/avatars/'+${theUser.avatar}}" alt="Avatar">
if you use like this (${theUser.avatar}) it will add ? in above version link look like this: /resources/images/avatars/photoname.png
As DimaSan said here https://stackoverflow.com/a/40914668/12312156
You should set image src like this:
<img src="../static/img/signature.png" th:src="#{img/signature.png}"/>

Yii2 add google font to head

I was wondering how do you add link tag/google font to head in yii2.
I want to add the following
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
I have found this documentation but doesn't mention anything about link/adding google font etc
The correct answer is to create a new AssetBundle.
While you can directly place the HTML for the fonts into the of your main.php file, this isn't the Yii way. If you have tried to load jQuery files this way, you might notice odd behavior when directly putting them into the HTML.
For example: Directly place the HTML tag for Bootstrap CDN into the head of your main.php. Then, somewhere in your code try to use the tooltip. You will get an error in your console that tooltip is not a function. - This is because the way Yii puts all your template files together, and at that time, Bootstrap is not available.
While simply loading a font probably won't cause any problems, it is a good idea to do things the way they were intended. Following MVC rules, properly documenting your code, and following the Yii best practices, will go a long way. Not only will you thank yourself a year later when you have to go back into a project, but the next guy will appreciate it. I can't stand going into systems, and seeing stuff thrown everywhere, chincy hacks, and spaghetti code, and no documentation or comments.
Correct Way:
Create a new AssetBundle. In your assets folder, you probably already have AppAsset.php. Duplicate it, and name it FontAsset.php.
Here is an example from my project, using 3 Google fonts.
FontAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FontAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'//fonts.googleapis.com/css?family=Open+Sans:400,700',
'//fonts.googleapis.com/css?family=Ubuntu:400,700',
'//fonts.googleapis.com/css?family=Oswald:400,700'
];
public $cssOptions = [
'type' => 'text/css',
];
}
In your layout, main.php for example. Right under where you see AppAsset::register($this)
main.php
use app\assets\FontAsset;
FontAsset::register($this);
For every layout file that you want to load those fonts, include the FontAsset.
The AssetBundle is basically a bundle of CSS and/or JS files and options. You could add another one for say JWPlayer say named VideoAsset, and add your JS/CSS files for JWPlayer in it.
Point being, you shouldn't be adding these things directly into the HTML of the layouts directly, as it can cause problems. Let the AssetManager handle them by declaring AssetBundles.
It might save you later down the road!
The best way is to create an asset bundle and add the link to the bundle.
You can find a complete guide here:
http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
You can put it directly in the head of the layout (file views/layouts/main.php)

Will html image paths still work after precompile?

I'm building a Rails app, but I'm using a plugin in which I have to render my images using only html.
Since I haven't deployed yet, all my images are in RAILS_ROOT/app/assets/images/, so to render an image I have to write the following code:
<img src="/assets/image.jpg">
But when I'm ready to deploy to the web and I perform a precompile, all my images are supposedly going to be moved to my public folder. Will the html still work to link to the image, or will I have to change to link to a different path?
The plugin I'm using is Typeahead:
application.html.erb*
<script type="text/javascript">
//....
$('#typeahead').typeahead(null, {
maxLength: 5,
displayKey: function(thing) {
return "<div class='typeahead'><img src='" + thing.image_url + "'></div>";
},
source: bloodhound.ttAdapter(),
});
</script>
things_controller.rb
def typeahead
#render json: Thing.where(name: params[:query])
q = params[:query]
render json: Thing.where('name LIKE ?', "%#{q}%")
end
*Thing.image_tag is currently set to "/assets/[image.jpg]", except for each thing it's adjusted with the proper file name.
Not only are they going to be in the public folder, but they'll be renamed to include the fingerprint.
You must use the Rails helpers for all assets, see how to here and read the rest of the guide while you're at it :)
I think you should use non-stupid-digest-assets gem as it copies all your assets(mentioned in assets precompile list) in public/assets folder and then you need not to change your code before/after compiling.To install, you just need to add it into your Gemfile.
gem 'non-stupid-digest-assets'
I hope it might help you.
Joe, my suggestion would be to create a directory in your public folder to house your images, instead us using the app/assets directory. The public folder will allow the assets to not be altered by the rails pipeline, and you can link to them reliably using any external services that need the images.
As stated in RailsGuides:
Assets can still be placed in the public hierarchy. Any assets under
public will be served as static files by the application or web server
when config.serve_static_files is set to true. You should use
app/assets for files that must undergo some pre-processing before they
are served.
So you would need to add this line in config/application.rb
config.serve_static_files = true
As described in Rails general configuration.
It looks like you're storing your image_url in your model, and that's not working because assets don't have fixed URLs in Rails. I would override the getter in your model to use the asset_path helper, so it translates the path when that attribute is read (e.g., when the JSON is generated).
Something like:
# thing.rb
[...]
def image_url
ActionController::Base.helpers.asset_path(read_attribute(:image_url))
end
[...]
Short answer, no.
But it isn't that big a deal to remedy. Just move the images you need to reference with html into your Public folder. Then you can simply reference them with this code:
<img src="/image_name.image_type">
and the html will link to the correct path, both before and after precompile. So you don't have to change any code before you deploy.
BTW: I assume image_tag and image_url are the same column and you just made a mistake in one of the two times you mentioned it. If that's the case, then don't forget to change it to simply "/[image.jpg]".

How to export Apiary Blueprint as PDF, stand-alone HTML or similar "deliverable"?

We need to export our Apiary Blueprint for task assignment purposes as a self containing "deliverable" like PDF or ZIP or similar. I'm aware of the feature request and the discussion below. Is it possible to "hack" something better than the poor html exporter? Maybe by injecting some css style into the page with chrome? Has somebody found a "good-enough" solution?
Ján Sáreník mentioned aglio, you can make it work locally by the following steps.
Save your API definition markdown (e.g. myfile.md)
Install aglio npm install aglio -g
Start aglio server aglio -i myfile.md -s
Open localhost:3000 and download the HTML file
Hack the HTML by commenting out the <div id="localFile" ...>...</div> warning
Hack the HTML by replacing http://localhost:3000/ with empty string everywhere
Aaand it's done.
You can use https://github.com/danielgtaylor/aglio to render API Blueprint into static HTML files which can be zipped (or maybe also PDF-exported, but I haven't tried).

How does Jade handle a src attribute? Why is it that /javascripts goes straight into the folder instead of /../public/javascripts?

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src="/javascripts/jquery-2.1.1.js")
script(src="/javascripts/global.js")
body
block content
Apparently, src="/../public/javascripts/jquery-2.1.1.js" doesn't work, but src="javascripts/jquery-2.1.1.js" works
The file structure is like so:
nodetest
public
javascripts
jquery-2.1.1.js
views
index.jade
Unless Jade actually creates index.html within the public folder? Is this correct?
first jade doesn't actually save an index.html to disk, it generates it on the fly during the request response cycle
second, by default, express is set up to treat public/ as the root directory for static files, so your reference to /javascripts/jquery-2.1.1.js points to public/javascripts/jquery-2.1.1.js
if you tried to load /views/index.jade or /index.jade it would 404 because Express won't find any matching static file
and finally src="/javascripts/jquery-2.1.1.js" (i.e. with a leading slash) should probably be how you reference it, because otherwise it's gonna look for child folders according to your url. (like, if you have js/jquery.js on the page my.domain/parent/child.html, the request would go to my.domain/parent/js/jquery.js