javaspring-bootembedded-tomcat-7

Expose resources using Spring embedded tomcat (.jar)


I am Using spring bootapp to build a rest-like api (which contains endpoint/controllers, services repositories ...)

I am running my app using the embedded tomcat approach and a simple .jar file produced using mvn "package".

One of the endpoints allows the UI to post an image in base64 format, and I am using the following method to convert it to image and store it to the server.

public static ImageData base64ToImage(String base64) throws IOException
{
    String[] imageDataArray = base64.split(",");
    String mimeType = imageDataArray[0].split(";")[0].split(":")[1];
    String ext = mimeTypeToExtension(mimeType);

    byte[] data = Base64.decodeBase64(imageDataArray[1]);
    String imageTitle = UUID.randomUUID()+"_"+getCurrentUnixTimestamp().toString() + ext;
    String filename = IMAGE_PATH + imageTitle;
    FileUtils.writeByteArrayToFile(new File(filename), data);
    return new ImageData(imageTitle, mimeType);
}

This is the point where it gets interesting..

I have no idea how to expose these images afterwords.

The file structure in the server is like so:

root
-- executable_embedded_tomcat_app.jar
   -- images 
      -- image1.jpg
      -- image2.jpg

Of course the following won't work: http://localhost:8080/images/image1.jpg

So the question: Is there a way to expose these resources - does Spring provide such functionality? Is my "executable jar + embedded tomcat" approach wrong?

Many thanks!

----Update----

As @DaveH suggested, I just added the following endpoint controller:

@RequestMapping(value="/images/{image:.+}", method=GET)
public byte[] getImage(@PathVariable String image) throws IOException
{
    InputStream in = new BufferedInputStream(new FileInputStream("./images/" + image));
    return IOUtils.toByteArray(in);
}

Solution

  • You could define an endpoint in your application that sits at /images and just reads the file from the file system and returns it to the client.