Where to upload an image/file to make it appear on HTML?

1.3k views Asked by At

Well,I'm working on an Eclipse Dynamic Web Project under Tomcat. I'm trying to make a web application/site.In a jsp/html page,there is a form where a user can upload a photo. I handle then this action from a servlet that has to store this image/file somewhere so as to make it possible the image appears whenever I want on the site.

Here is the problem.I started by storing it on my file system,(path in a database) but when I wanted to retrieve it the page didn't appear. I guess the reason is here:

Why can't I do <img src="C:/localfile.jpg">?

Then,I tried to store the file in the eclipse project folder(WebContent/folder) where I've stored manually some images that do appear.

    File folder=new File("/TED/res/img");
    File file=new File(folder,fileName);
    System.out.println(file.toPath());
    Files.copy(fileContent, file.toPath());

But this exception happens:

java.nio.file.NoSuchFileException: /TED/res/img/2017-08-13-123524.jpg

It's one the line of files.copy command which means that

new File(folder,fileName) that I tried failed

What should I do? From what I've read,I understood that also saving file in the IDE's project folder is also wrong but what other choice do I have?

1

There are 1 answers

0
Akber Choudhry On BEST ANSWER

Ultimately, the project will be deployed to a server. As such, there are three distinct issues:

  1. Uploaded user content location: content like images should be uploaded to a folder outside your web app (project). Images inside the web app (project) should be those that are necessary for the application and provided by the developer, not user-generated.
  2. In Eclipse, during development and testing, you will want to serve these images through Tomcat. There are many ways to do this. Tomcat configuration is probably not the best for this - please read the answer and discussion here: Simplest way to serve static data from outside the application server in a Java web application
  3. Once the application is deployed to the server, Tomcat will most likely run behind a Web server like Apache or Nginx. In this case, the external image folder and its contained files can be served directly by the Web server. Even if you implemented a servlet in (2) for local testing with Eclipse and this servlet is part of the code that is deployed, it will not be invoked as the URL will be intercepted by the Web server before it reaches Tomcat. For example, if your uploaded image folder is C:\images on your development environment, it can be served by the servlet using the technique in (2) as /images/*. When deployed to a server, the Web server can be configured to servet /images/* from /srv/content/images and this request will never reach Tomcat.