Home >Database >Mysql Tutorial >How to Store and Retrieve Images in a Java Web App Without Using a Database?

How to Store and Retrieve Images in a Java Web App Without Using a Database?

Linda Hamilton
Linda HamiltonOriginal
2024-11-18 21:40:021057browse

How to Store and Retrieve Images in a Java Web App Without Using a Database?

Storing and Retrieving Images in a Java Webapp

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn