How I save and retrieve an image on my server in a java webapp [duplicate] How I save and retrieve an image on my server in a java webapp [duplicate] mysql mysql

How I save and retrieve an image on my server in a java webapp [duplicate]


instead of writing it to my C drive I'm going to run it on the server, but where should I store the image to later retriev and display in an xhtml file?

That depends on how much control you have over configuring the server. Ideal would be to configure a fixed path outside the Tomcat webapps folder. For example, /var/webapp/upload. You can set this path as a VM argument or environment variable so that your webapp can retrieve it programmatically without the need to change the code.

For example, when specifying as VM argument -Dupload.location=/var/webapp/upload, you can complete the upload 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();// Now store it in DB.

As to serving the file back, most ideal would be to add the upload location as a separate <Context> to Tomcat. E.g.

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

This way you can access it directly by http://example.com/uploads/foo-123456.ext

If you have zero control over configuring the server, then, well, storing in the DB or sending to a 3rd party host such as Amazon S3 is your best bet.

See also:


I would consider allowing the user to upload to Amazon S3 directly. Amazon offers a service for that. Using that service, the client would post a form with the file directly to S3. Once the file has arrived there, Amazon will redirect the client to one of your endpoints, to confirm that the data has arrived, passing you the relevant details.

The benefits are:

  1. Your server does not spend a lot of time in receiving huge files. You can spend your CPU cycles on something a little bit more interesting.
  2. The availability guaranteed by storing it on S3 is probably better then what you would get by storing it on your own Windows box.
  3. It scales. At some point, your filesystem will run out of space. (Or you reach the limit of what you can store inside a folder.)


I'd suggest that you save your images in a subfolder which is in your application's WEB-INF folder. Remember that when you use Tomcat, your WAR files will be extracted automatically. This approach also has the advantage that you can always migrate your application to another server, you only have to save the path relative to WEB-INF folder in your DB.