html page can't find asset from Go web server - html

I have a Go HTTP web server and I'm loading static assets like so:
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))
The directory assets exist at the directory the web server is running, and the image file assets/images/logo.svg exist.
If I try going to http://localhost/assets/images/logo.svg it redirects to http://localhost/.
From an HTML page I have the following:
<img src="assets/images/logo.svg">
This fails to load the image.
I then tried the following as well with no luck:
<img src="./assets/images/logo.svg">
<img src="//localhost/assets/images/logo.svg">
Unsure what I'm doing wrong to host static files and being able to use them from html.
EDIT
I've added the code for everything here.
Along with a photo showing the broken images.

Try to modify the line from:
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("assets/")),
),
)
to
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("./assets/")),
),
)
Please note, your img->src should be something like this assets/images/logo.svg
EDITED:
The below image is the response to the comment link:

Related

TemplateDoesNotExist at /welcome_page/

I'm new in coding field. I decided to start a project with Django & Python, but I got stuck due to some errors. For the past 3 weeks, I tried to figure out what was the issue but couldn't find it. I will appreciate it if anyone help.
when I run my code, I get as an error, "TemplateDoesNotExist at /welcome_page/"
Everything as been specified but I'm still getting the same error
Here is the error page:
TemplateDoesNotExist at /welcome_page/
content of the welcome page:
Content of my the welcome page
my URLs :
URLS where I defined welcome page
My base content:
My base content
the place where the welcome page is calling from:
The place where the welcome page is calling from
My root to the welcome page from my C: drive:
My root to the welcome page from my C: drive
In your logout_request() view the last line is this:
return redirect("templates/welcomepage.html")
That's trying to redirect the user to a template. It should be redirecting to a URL.
In your urls.py the Welcome Page view has name="welcomepage" - this is what you use to refer to that URL. So change that line in your view to:
return redirect("welcomepage")
That will return the user to the "welcomepage" URL, which uses the views.welcome_page view, and the templates/welcome_page.html template.
By the way, if your welcome_page view is a class, as opposed to a function (I can't see it in your screenshot, so can't tell) then it's more normal in python to capitalise it: WelcomePage. Or WelcomePageView. Functions are lowercase (welcome_page).
If I see it right, you redirect to /templates/xxx.html but that path is not defined in your paths. The templates directory is the internal location, but the user can only see what is defined in the paths.
You should also better redirect ti the name of the page defined in the paths. Please post your settings.py maybe there is also a problem with the search path for templates.

get a resource path in MFC

I am trying to build HTML in my MFC application using class CHtmlEditView.
So I want to add an image, currently I am using <img align=\"baseline\" alt=\"\" src=\"C:\\cry.png\" border=\"0\" hspace=\"0\"> and its working all fine.
Now, I have to replace this src=\"C:\\cry.png\" local path. So I have added this to resources and <img align=\"baseline\" alt=\"\" src=\"\\res\\smiley.png\" border=\"0\" hspace=\"0\"> its not getting image path. I am not sure how to give a path a image from resources. I have seen LoadBitmap() and LoadImage() but do know how to get a relative path of resource.
Your target URL will be something like this: res://yourapplication.exe/agent.png
Please note that you will need to import your image resources just like this:
Go to Resource View
right click and select Import context menu option
select your image file
Please note that as the result you should have the following in your .rc file:
STARTPAGE.HTML HTML "res\\startpag.htm"
AGENT.PNG HTML "res\\agent.png"

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}"/>

How to access image files outside project folder in html?

I put the user uploaded image files on separate disk partition on my local dev server(OS windows) which is outside of project folder. I need to access those image files in html pages of web app.
I tried out giving paths like: http://localhost:8080/C://tmp/thumbnails/pl_2001.JPEG but no help. Image is not fetched. How to properly access such files in html pages ?
You will have to use rewrites for this so you don't display sensitive folder names.
if you are using php you can use .htaccess rewrites for a slug something like images/someimage.mime and split/get what's after images/ and have a php function that takes the filename and makes sure it exists and if you want you can check if its a valid mime then send a header to say its a image/somemime so the browser can display the image instead of gibberish it will display without it.
$filename = "C://tmp/" . $file;
if(file_exists($filename)){
$img = getimagesize($filename);
if(in_array($img['mime'], array('jpg','jpeg','gif','png','etc'))){
header("Content-type: image/" . $img['mime']);
readfile($filename);
}else{
//default image
}
}else{
//default image
}
I haven't tested this but it should give you a idea on getting you started. If this isn't the language you are looking for try searching for something similar for your language you are using.

Store Images in App_Data and address them absolute make errors

I've generated an image tag like below:
<td>
<img src='#item.SourceAddress' alt="#item.Description"/>
</td>
and the result is somrthing like this:
<td>
<img src='C:\Users\leo\Workspace\Team Foundation Server\Sources\HRS\HRS\App_Data\user\Photos\test.jpg' alt="desc"/>
</td>
The problem is I only see blank space and no image at all(in firefox I only see alt text). the path is correct. I copied the img tag itself into another html file and I see the image crystal clear.
somrthing that might help: I opened the source with firefox and when I clicked on source of image I got following error:
Firefox doesn't know how to open this address, because the protocol
(c) isn't associated with any program.
and sorry for terrible english by the way.
Edit: I Edited the title. It is make more sence now!
This may be due to you providing a local path name (i.e. a directory in C:) rather than a relative path via Razr. If you start debug in Firefox then the console output sometimes eludes to this.
You could try something similar to:
<img src="#Url.Content(Item.SourceAddress)" alt="desc"/>
And check that SourceAddress is in the format of:
~/MyImages/Photos/test.jpg
Also worth checking all the obvious things like double quotes over single quotes etc.
Finally found out what is the problem!
First of all I used App_Data Folder to store files. this folder is special purpose and is used to store some special database files and IIS wont give direct access to this folder. and I had to make another folder like Image and store files there.
Second problem is I gave the path directly from Root (C:\...). The Web Browser doesen't have access to the Server File System Directly (Due to some security reasons). Because of this I had to gave the path relative address. The absolut path should be used by Server Code only and not in html source.
I managed to convert absolute path to relative like below:
`public static class HttpServerUtilityExtensions
{
public static string RelativePath( this HttpServerUtilityBase utility, string path, HttpRequestBase context )
{
return path.Replace( context.ServerVariables[ "APPL_PHYSICAL_PATH" ], "/" ).Replace( #"\", "/" );
}
}`
and:
``