Serve both static files from my project (i.e. scripts) and images that users upload

84 views
Skip to first unread message

SG

unread,
Jan 29, 2017, 4:34:08 PM1/29/17
to sparkjava

Hi,

I'm quite new to Spark and trying to figure out how do I achieve the following behavior.

I have on my server two types of files that I want to access from the client side:

  1. 1. JS/CSS scripts (static), their location is the root directory of my webapp.
  2. 2. Images that are not part of my source code. They are uploaded by users to another directory on the server, let's say their location is /tmp/photos.

As far as I understand from the documentation with externalStaticFileLocation() or staticFileLocation() I can only set one of these locations to be accessed. How can I serve these two locations together?


Tried to ask the same on stackoverflow, but no answers.

Hopefully here I'll get some more help.


Thanks :)

domin...@gmail.com

unread,
Jan 30, 2017, 2:24:29 PM1/30/17
to sparkjava
Sorry, that isn't possible. (As I'm sure you have already figured out.)

This method in the StaticFilesConfiguration Class it only takes a single String representing the folder. Although it does interact with a collection of AbstractFileResolvingResource which looks promising.

public synchronized void configureExternal(String folder) {
Assert.notNull(folder, "'folder' must not be null");

if (!externalStaticResourcesSet) {
try {
ExternalResource resource = new ExternalResource(folder);
if (!resource.getFile().isDirectory()) {
LOG.error("External Static resource location must be a folder");
return;
}

if (staticResourceHandlers == null) {
staticResourceHandlers = new ArrayList<>();
}
staticResourceHandlers.add(new ExternalResourceHandler(folder, "index.html"));
LOG.info("External StaticResourceHandler configured with folder = " + folder);
} catch (IOException e) {
LOG.error("Error when creating external StaticResourceHandler", e);
}

StaticFilesFolder.externalConfiguredTo(folder);
externalStaticResourcesSet = true;
}

}

Perhaps a fork and pull request with your feature?

SG

unread,
Jan 31, 2017, 12:55:14 AM1/31/17
to sparkjava
Hi,

Thanks for replying.
So can I achieve this functionality in any other way? I mean, this is a pretty basic goal to be able to serve these two types of files. Every web server does it eventually.
Any ideas?

domin...@gmail.com

unread,
Feb 8, 2017, 3:56:49 AM2/8/17
to sparkjava
I hit this thing more often than I'd like. I look at it this way. 

Spark isn't a complete replacement for a full web server. If you need a full web server: Jetty

If you like Spark's minimal take on web but you need a feature that is hidden or unavailable, drop Spark into your full web server. http://sparkjava.com/documentation.html#other-webserver

Firing up an embedded Jetty is pretty simple these days, and then dropping Spark into that container is also dead brain easy. 

Hope this helps.
Reply all
Reply to author
Forward
0 new messages