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
Release: 2024-11-18 21:40:02
Original
1039 people have browsed it

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"));
Copy after login

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
Copy after login

Retrieval:

Add the upload location as a separate context to Tomcat:

<Context docBase="/var/webapp/upload" path="/uploads" />
Copy after login

Now, the image can be accessed directly via a URL like:

http://example.com/uploads/foo-123456.ext
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template