Home >Database >Mysql Tutorial >How to Efficiently Store and Retrieve Images in a Java Web Application?
Saving an Image to the Server
To save an image to the server, specify a fixed path outside the Tomcat webapps folder. For instance, if you create a folder named "upload" at "/var/webapp/", you can set it as a VM argument (-Dupload.location=/var/webapp/upload) or environment variable.
Using this path, complete the upload process as follows:
Path folder = Paths.get(System.getProperty("upload.location")); 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(); // Store it in DB
Retrieving an Image from the Server
The ideal way to retrieve an image is to add the upload location as a separate Context to Tomcat:
<Context docBase="/var/webapp/upload" path="/uploads" />
This allows direct access to the image via a URL such as http://example.com/uploads/foo-123456.ext.
If server configuration control is limited, consider storing the image in the database or using a third-party host like Amazon S3.
Additional Resources:
The above is the detailed content of How to Efficiently Store and Retrieve Images in a Java Web Application?. For more information, please follow other related articles on the PHP Chinese website!