javajsffile-uploadprimefacesrealpath

uploading file to web root directory using jsf Primefaces


I am trying to store client logo into "src/main/webapp/clientImage/clientcode" clientcode directory will be created based on different-2 client.
For Example if client Code is TEST then the complete path will be like "src/main/webapp/clientImage/TEST" and when we upload client image then client logo will come under "TEST" directory .
So after uploading client logo ( suppose image name is "test.jpeg" ,then complete directory will be "src/main/webapp/clientImage/TEST/test.jpeg". The Code to upload client logo is::

`public boolean upload(UploadedFile uploadFile) {
String LOGO_PATH= "/clientImage/";
String fileName = uploadFile.getFileName();
String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath(LOGO_PATH + selectedClient.getClientCode());
File f = new File(realPath);
if (!f.exists()) {
        f.mkdirs();
        logger.debug("Directory created : {}", f.getName());
}
try {
new UserUtils().copyFile(fileName, uploadFile.getInputstream(), realPath);
            selectedClient.setLogo(fileName);
saveClient();
FacesMessage msg = new FacesMessage("Success! ", uploadFile.getFileName() + " set as logo.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return true;
} catch (IOException e) {
    logger.error("{}", e);
    return false;
}
}

`

Problem:: My problem is when i am uploading the logo for TEST client the realPath i am getting is "C:\Users\narendra\tls_workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\iclock\clientImage\TEST"

where the realPath supposed to be "src/main/webapp/clientImage/TEST/test.jpeg" and logo should be store into TEST directory,but logo is even not comminng into that directory


Solution

  • You're not running the source itself. Your source files get compiled into classes, then your classes and resources get packaged into a Web Application Archive - a WAR file. So your realPath isn't in src, it's wherever your WAR is deployed. In your case, its in Eclipse's tmp files, because you're running it from Eclipse.

    The notion of uploading files to the source directory is nonsensical, because your source directory won't be deployed to the server - the packaged WAR will. If you sell your web application, you're probably not gonna send your source to your customer - you'll send them an executable, i.e. a WAR file.

    You shouldn't keep user data in your WAR either. Your WAR should be immutable during its runtime. Instead you should ask your server or Java for a Temp directory, or for some kind of a data directory. E.g. Wildfly servers have these system properties:

    jboss.server.data.dir - directory the server will use for persistent data file storage jboss.server.temp.dir - directory the server will use for temporary file storage