Uploading a file to a directory on the server using Java and JSP - cannot get the correct path

In my vps, I want to upload a file to the Logos directory. The directory structure is as follows on my vps -
/home/webadmin/domain.com/html/Logos

When a file is downloaded through my jsp page, this file is renamed, and then I want to put it in the Logos directory .... but I can not find the path in the servlet code.

Servlet code snippet -

String upload_directory="/Logos/"; // path to the upload folder

File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);

//.....
//file saved to directory
//.....

I tried a lot of options, but still fail. What is the correct way to indicate the path?

Edited
The problem with using getServletContext () is that it returns the path to the directory where Tomcat and my webapp ..., while I want to get to the directory where my html and image files are located, in the vps root directory. How to indicate this path?

    String server_path = getServletContext().getRealPath("/"); // get server path.                      

    //server_path = /opt/tomcat6/webapps/domain.com/

    String upload_directory = "Logos/"; // get path to the upload folder.

    String complete_path = server_path + upload_directory; // get the complete path to the upload folder.

    //complete_path = /opt/tomcat6/webapps/domain.com/Logos/

    File savedFile = new File(complete_path,"NewLogo.jpg");

    //savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg 
+3
source share
4 answers

It is common practice to create a path to configure the repository - either through some file application.properties, or if you do not have such a properties file - as context-paramin web.xml. There you define the path as an absolute path, for example:

configuredUploadDir=/home/webadmin/domain.com/html/Logos

Get this value in your code (depending on how you saved it) and follow these steps:

File uploadDir = new File(configuredUploadDir);

. , .

+3

jsp .

1) String serverPath = getServletContext(). getRealPath ( "/" );

-.
: "D:\local\tomcat-6.0.29\webapps\myapp" , sysout myapp.

, , . , myapp\data​​strong > , \data\filename serverPath, .
, .

2) ,

System.getProperty( "TOMCAT_HOME" )

3) <init-param>

, .

,

CIGNEX Technologies

+2

Well, the problem is that the file constructor does not create the file, it only prepares for creation, and then, after creating the file instance, you have to call the createNewFile () method, and all that.

+1
source

The path "/ Logos /" will try to create a file in the root of your system, which you do not want. Take a look at the ServletContext.getRealPath () method.

0
source

Source: https://habr.com/ru/post/1786189/


All Articles