The simplest way would be to configure a path[a directory] in your web.xml and use the same path to upload/download images based on the image name specified.
In your web.xml:
<web-app ...>
<context-param>
<param-name>RESOURCE-PATH</param-name>
<param-value>d:/My-Uploads</param-value>
</context-param>
</web-app>
In your Servlet when saving:
// TODO: Move the image writing code to a separate utility
// class to maintain a sane level of abstraction
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
String path = getServletContext().getInitParameter("RESOURCE-PATH");
OutputStream out = //retrieve the file stream
String imageName = request.getParameter("image-name");
File dir = new File(path);
File file = new File(dir, imageName);
// write from the servlet request stream to this file
}
In your Servlet when retrieving:
// TODO: Move the image reading code to a separate utility
// class to maintain a sane level of abstraction
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
String path = getServletContext().getInitParameter("RESOURCE-PATH");
String imageName = request.getParameter("image-name");
File dir = new File(path);
File file = new File(dir, imageName);
// Check file existence; throw appropriate error if not present
// Write the contents of the file to the servlet response stream
}
- Of course there might be problems implementing this approach, but this is as simple as it gets.
- You can also store your images in a database as BLOB to get all the benefits offered by an RDBMS if required.
- You can also store the images relative to your web application root instead of just any random location on …