Question:
How can I store and retrieve an image on a server in a Java web application without storing it in a database?
Answer:
The optimal location for image storage depends on the server configuration.
Ideal Storage Location:
Configure a fixed path outside the webapp's directory, such as /var/webapp/upload, as a VM argument or environment variable. This path can be retrieved programmatically. For instance, using the -Dupload.location=/var/webapp/upload VM argument:
Path folder = Paths.get(System.getProperty("upload.location"));
Example Storage and Retrieval Code:
Assuming the existence of an uploadedFile representing the image:
Storage:
String filename = FilenameUtils.getBaseName(uploadedFile.getName()); String extension = FilenameUtils.getExtension(uploadedFile.getName()); Path file = Files.createTempFile(folder, filename + "-", "." + extension); try (InputStream input = uploadedFile.getInputStream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } String uploadedFileName = file.getFileName().toString(); // Save uploadedFileName in database
Retrieval:
Add the upload location as a separate context to Tomcat:
<Context docBase="/var/webapp/upload" path="/uploads" />
Now, the image can be accessed directly via a URL like:
http://example.com/uploads/foo-123456.ext
The above is the detailed content of How to Store and Retrieve Images in a Java Web App Without Using a Database?. For more information, please follow other related articles on the PHP Chinese website!