Can not find "locale.properties" file from PDF.js - html

I use this plugin: PDF.js.
I am trying to solve the problems that show in console log.
Follow image:
Here is a simple project ready, only download and run project you will see the same problem. I've tried everything and I can not solve a problem.
Follow html:
<div style="width: 800px; height: 500px;">
<iframe width="800" height="500" id="iframePdfViewer" seamless="seamless" scrolling="no" src="~/Scripts/pdfjs-dist/web/viewer.html"></iframe>
</div>
See another image that contains "locale.properties" file:
And I also get a lot of warnings from l10n.js. I downloaded it here: http://mozilla.github.io/pdf.js/ by clicking the "download" button.
Any solution ?

Adding .properties MIME type configuration inside web.config file should work:
<configuration>
<!-- other stuff -->
<system.webServer>
<staticContent>
<mimeMap fileExtension=".properties" mimeType="application/octet-stream" />
</staticContent>
</system.webServer>
</configuration>
If the project is already deployed in IIS (not IIS Express), go to site name => MIME Types => Add, and set .properties extension with application/octet-stream type as in provided image below:
Here is the console log view with all l10n.js errors disappear:
The reason behind usage of application/octet-stream is that the corresponding file should be treated as stream, even file contents are readable and stored in text format.
Reference: l10n.js - locale.properties 404 (Not Found)

If you are using .net core (2.1) try to add .properties as static file in your "public void Configure(IApplicationBuilder app, IHostingEnvironment env)" method
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".properties"] = "application/octet-stream";
app.UseSpaStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});

Inspired by Lukáš Janeček, If you are using .net core(3.1). try to add the following code to your public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".properties"] = "application/octet-stream";
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = provider
});

Related

Asp net core - can't see new added icon in browser

We are running an ASP NET CORE MVC service (.Net core 2.2) that acts as our client.
I've added a simple HTML with an img tag to one of our views.
<a class='icon-suspend-wait txt-color-orange'>
<img src = '/Content/img/icons/icon-suspend-wait.png' alt='Waiting for suspend' />
<span class='vertical-middle'>Waiting for suspend</span>
</a>
Now, I've added a new png file named "icon-suspend-wait.png" under
Content\img\icons folder
icons folder screenshot
When I navigate to the website I can see the added HTML part but not the icon.
So I opened chrome devTools AND under the "Elements" tab, I can see the new HTML part (the ).
elements section
But under the "Source" tab I can't see the icon I've added:
source section
When I try to open the icon link in a new tab from the "Elements" tab, I get the following error:
404 error
What i tried to do:
Clean and recompile the project.
Hard refresh for the browser.
Disable the cache from the DevTools (Network -> Disable Cache).
Nothing seems to work.
What am I missing ?
If you want to serve files outside of web root,you need to add the following configuration in StartUp.cs:
...
using System.IO;
namespace ClientSideDemo5
public class Startup
{
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "Content")),
RequestPath = "/Content"
});
app.UseRouting();
...
}
}
img:
<img src = '~/Content/img/icons/icon-suspend-wait.png' alt='Waiting for suspend' />

HTML <object> - download file if it cannot be loaded

I have a web application that serves files for viewing. If it's a PDF, I simply attach it to an <object> element. However, the app supports serving word, excel, and powerpoint files. I have tried looking for ways to preview them online, but apparently we do not have the proper technology for that (at least not natively in a browser). So instead, I want the user to download the file to view locally.
The front-end is built with React and the back-end with Spring Boot. Currently, all static resources that are documents (PDF's, docs, spreadsheets, etc.) are served under the "/document-files/**" ant-matcher. Additionally, these resources can only be viewed privately, meaning that you have to be logged in to the application to view them. Here's how part of my SecurityConfig file looks like:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String documentRootPath = "file:" + this.documentRootPath;
registry.addResourceHandler("/resources/**").addResourceLocations("resources/");
registry.addResourceHandler("/document-files/**").addResourceLocations(documentRootPath);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // ant matchers below are api routes and the baseUri for serving documents
.antMatchers("/clients/**", "/projects/**", "/documents/**", "/document-files/**").authenticated()
.anyRequest().permitAll() //... additional method chaining omitted for brevity
}
The problem is apparently just on the front end. I don't think it has anything to do with the configuration, but I posted it for reference. With this configuration I can download and preview PDF files just fine, using <object> but for all other files, the file does not load, so in <object> I add a link to open the file like so:
render() {
// some code omitted for brevity
return (
<Module>
{!this.state.currDoc ? (
<ul className={this.state.displayType}>{list}</ul>
) : (
<object
data={"/document-files" + this.state.filePath}
type={this.mimeTypes[document.fileType]}
title={"Current Document: " + document.description + "." + document.fileType.toLowerCase()}>
{document.fileType === "PDF" ? "File could not be loaded!" : <div id="download-prompt">This file cannot be previewed online, click below to download and open locally.<a href={"http://localhost:3000/document-files" + this.state.filePath} download>Open</a></div>}
</object>
)}
</Module>
);
}
Upon clicking, the "save as" dialog box appears with the file name populated and the correct mime type but once I hit save, Chrome displays "Failed - No File". I have tried writing the href with and without the hostname. I've also tried removing the download attribute, but it redirects the page back to itself. I've even tried onLoad attribute on <object> but apparently that only works for images. I checked the network tab on dev tools and there is no record of the file being downloaded, unlike PDFs where the request is noted down.
How can I make non-PDF files download correctly using this setup?
Thanks to javilobo8's GitHubGist, I found a way to download files using Axios, which library I was already using in my app to begin with. For quick reference, here is his code:
axios({
url: 'http://localhost:5000/static/example.xlsx',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
Also, there's multiple ways to work with Blobs, depending on if you're in IE, a browser that supports HTML5's Blob object, or another browser. This question helps split the code in 3 ways to form the dataUri for downloading raw data.
After setting up my <a> tag, I just trigger the click event and the non-PDF file downloads!

How to cache images on the client that are served from a controller action

Setup
I have a website written in ASP.NET MVC 5.2.3 that displays a number of images. Some of these images are static and are served up from the file system directly in the view:
<img src="~/Content/images/StaticImage.jpg?1" />
The rest of the images come from a database and are served up using a controller action:
Controller
public ActionResult GetDatabaseImage(long rowId, long rowTimestamp)
{
return this.File(GetDatabaseImage(rowId, rowTimestamp), "image/jpeg");
}
View
<img src="#Url.Action("GetDatabaseImage", "Image", new { rowId = Model.RowId, rowTimestamp = Model.RowTimestamp })" />
I want all of these images to be cached on the client and in the case of the database images, on the server as well and hence I have added an OutputCache attribute to the GetDatabaseImage action:
[OutputCache(Duration = int.MaxValue, VaryByParam = "*")]
and also used the following configuration in web.config:
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
Problem
The caching works perfectly for the static images, the same can't be said for the database images. Here is what Chrome Dev tools is showing me when I access the page (after it's already been loaded once).
As you can see, the static image is cached correctly on the client and no server connection is made but for the database image it is still checking the server to see if the image has been modified. I do not want it to do this as I've specified a cachebuster parameter (rowTimestamp).
Question
How can I get the database images to behave in the same way as the static images?

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

Accessing "test.html" page from the browser at the following url http://mysharepointservername.com/test.html

Which directory should I use to place test.html to access it via the browser by using the following url:
http://mysharepointservername.com/test.html ?
If I place the file to C:\inetpub\wwwroot\wss\VirtualDirectories\80 , I get 404 not found error.
Is there another directory I should use to place test.html?
Thank you in advance
You can create a module in sharepoint and place test.html under that module.
And in elements.xml write:
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="CustomPage" Url="">
<File Url="CustomPage\test.html" Name="test.html" Type="Ghostable" />
</Module>
</Elements>
And deploy this module using feature.
In this way you can access the page with http://mysharepointservername.com/test.html