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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With