Express has the ability to serve static files at a different virtual location:
app.use('/static', express.static('public'))
However, I'm using Java for my server using Spark Java. I know how to serve static files, but is it even possible for Spark Java to serve static files at a virtual location? If it is possible, how? I have searched for a while, but all the tutorials I find just tell me how to serve static files, not serve static files at a virtual location.
Edit: an explanation of "virtual location": Lets suppose this is the current dir:
public/
|-----index.html
|-----style.css
|-----etc...
Then, we can get a webpage with http://localhost:8080/public/index.html
However, I want to change it so that I have it can get the webpage with
http://localhost:8080/somedir/virtual/pathindex.html
When using Spark-Java, the Spark
class contains the staticFiles
static import, which provides a set of static file utility methods.
One of these is externalLocation(String externalFolder)
.
So, for example, you can define your Spark application, and in the init()
method you can define the external location:
Spark.staticFiles.externalLocation("[your external path here]");
This location can be outside of the application's classpath.
This is documented here.
Regarding a "virtual" location: the word "virtual" suggests a directory which is just a Linux-style symlink or pointer to some other location on the file system. As long as your application has permissions to access the target of the symlink/pointer, this should work OK.
(I have not tried this with Windows shortcuts - those may not work.)
Just to note: If you define your external location as this:
staticFiles.externalLocation("public");
then you will not be able to access resources at:
http://localhost:8080/public/index.html
Instead you will need to use:
http://localhost:8080/index.html
In this case, public
is the starting point. If you want to explicitly include public
in your URL, you would need to add a subdirectory called public
:
public/
|----public/
|-----index.html
|-----style.css
|-----etc...
Now this will work, as you have it in your question:
http://localhost:8080/public/index.html
So, unfortunately, I guess there is no way to do it pragmatically and you have to use a symlink. That's ok, thanks!
Thank you for the feedback. Just to clarify - did you mean "do it programmatically"? In other words, you want to dynamically change the location of
public
after the application has started? If that is the objective, then you are correct, there is no way of doing that. Once the static file location has been defined, it cannot be changed, while the application is running. Please correct me if I have misunderstood your comment.yes you are correct