0

Hopefully a simple question :

I have created code to get a username from a log in page :

private String username;

@PostConstruct
public void init() {
    username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}

but what I want to do is add the username to end of this destination :

private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/";

how would I do it so it the destination would call the username to place the document in a file specific to that user ? this is all in the same bean

This is my currently bean

@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
    File theFile = new File(destination + username); // will create a sub folder for each user 

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void copyFile(String fileName, InputStream in) {
        try {


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(theFile + "/" + fileName)); // cannot find path when adding username atm
            System.out.println(theFile); //testing 

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

CURRENT EDIT :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
    File theFile = new File(destination + username); // will create a sub folder for each user 

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public File getDirectory(String destination, String username) {
        //set the user directory from the destinarion and the logged user name
        File directory = new File(destination, username);
        //check if the location exists
        if (!directory.exists()) {
            //let's try to create it
            try {
                directory.mkdir();
            } catch (SecurityException secEx) {
                //handle the exception
                secEx.printStackTrace(System.out);
                directory = null;
            }
        }
        return directory;
    }


    public void copyFile(String fileName, InputStream in) {
        try {


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
            System.out.println(directory); //testing 

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

EDIT ::::

Now saying directory, in out = new FileOutputStream(new File(directory)); cannot find symbol also I get realFile not used

current code :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
    File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) 

    public File getDirectory(String destination, String username) { // currently not working, is not calling the username or directory 
        //set the user directory from the destinarion and the logged user name
        File directory = new File(destination, username);
        //check if the location exists
        if (!directory.exists()) {
            //let's try to create it
            try {
                directory.mkdir();
            } catch (SecurityException secEx) {
                //handle the exception
                secEx.printStackTrace(System.out);
                directory = null;
            }
        }
        return directory;
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            //handle the exception
            e.printStackTrace();
        }
    }

 public void copyFile(String fileName, InputStream in) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out = null;
        try {
            File realFile = new File(userDirectory, fileName);
            out = new FileOutputStream(new File(directory));
            int read = 0;
            //1024 must be a constant
            //also, it must be 4098 (4 KBs) for better performance
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            out.close();
        }
    }
}

EDIT AGAIN LOL :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads (will change this thanks to adivce )
    File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) 

    public File getDirectory(String destination, String username) { 
        // currently not working, is not calling the username or destination 
        //set the user directory from the destinarion and the logged user name
        File directory = new File(destination, username);
        //check if the location exists
        if (!directory.exists()) {
            //let's try to create it
            try {
                directory.mkdir();
            } catch (SecurityException secEx) {
                //handle the exception
                secEx.printStackTrace(System.out);
                directory = null;
            }
        }
        return directory;
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            //handle the exception
            e.printStackTrace();
        }
    }

    public void copyFile(String fileName, InputStream in) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out;
        try {
            File realFile = new File(userDirectory, fileName);//realFile variable not used
            out = new FileOutputStream(new File(userDirectory));// no suitable constructor found for File(File)
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
}

    /**
    public void copyFile(String fileName, InputStream in) {
        try {


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
            System.out.println(directory); //testing 

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
*/

This is my latest version of the code, I have tried to modify it, but it current throwing a few errors, I have added the errors in comments in the code, also is the public File getDirectory(String destination, String username) in the right place ? Thanks, I never would have thought I would have to do this much work to do something simple ! :D

Lain
  • 2,166
  • 4
  • 23
  • 47
user1924104
  • 891
  • 2
  • 16
  • 38
  • If you want to create a `File` object using this `destination` as the parent directory and the `username` as the directory to save the real file, you can do `File theFile = new File(destination + username, fileName);`. Am I guessing right? – Luiggi Mendoza Jan 30 '13 at 22:24
  • Thanks thats exactly what i was looking for, quick question, how can i add a \ between username and fileName ? – user1924104 Jan 30 '13 at 22:31
  • figured it out hopefully ! thanks for the help – user1924104 Jan 30 '13 at 22:38
  • Ok new problem, if the path does not exist is there a way to create it – user1924104 Jan 30 '13 at 22:40
  • Do not store uploaded files in deploy folder. http://stackoverflow.com/questions/14211843/how-to-save-uploaded-file/14214223#14214223 – BalusC Jan 30 '13 at 23:55
  • Thanks you say not to use the web-inf to store the uploads, where would be a more suitable place to store them ? i need to access them later on – user1924104 Jan 31 '13 at 16:38

1 Answers1

1

Your problem is more related to File class usage than a JSF problem.

You can use this class to handle files or directories. To start with, you can have two methods:

  • a method that will retrieve the user directory

  • a method that will save the file in the user directory

Basic example:

//note: this must be moved to an utility class
public File getDirectory(String destination, String username) {
    //set the user directory from the destinarion and the logged user name
    File directory = new File(destination, username);
    //check if the location exists
    if (!directory.exists()) {
        //let's try to create it
        try {
            directory.mkdir();
        } catch (SecurityException secEx) {
            //handle the exception
            //this is a naive way to do it
            secEx.printStackTrace(System.out);
            directory = null;
        }
    }
    return directory;
}

public void saveFile(String fileName, byte[] data) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        //create the real file using the directory as parent directory
        //we'll give the file name too
        //check the different constructors for File class
        File realFile = new File(userDirectory, fileName);
        //save the file the way you want/need...
        //this should be also in an utility class
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(realFile);
            fos.write(myByteArray);
        } catch (Exception ex) {
            //handle the exception
            ex.printStackTrace(System.out);
        } finally {
            if (fos != null)
                fos.close();
        }
    }
}

References:


Based on your question edit, you must modify the copyFile in order to look as the saveFile method that I proposed. I'll change the implementation to use an InputStream.

public void copyFile(String fileName, InputStream in) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out;
        try {
            File realFile = new File(userDirectory, fileName);
            out = new FileOutputStream(new File(userDirectory));
            int read = 0;
            //1024 must be a constant
            //also, it must be 4098 (4 KBs) for better performance
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            out.close();
        }
    }
}
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thank you, i have added my current bean to my original question, i will try to integrate your example to it – user1924104 Jan 30 '13 at 23:04
  • How would you integrate your code with my code i have posted, as i am a little bit confused, as can i only use your first section of code and intergrate that, however when i do this it still will not run, posted above – user1924104 Jan 30 '13 at 23:11
  • the getDirectory section is not pulling the username or destination from the bean, have i placed it the wrong place ? – user1924104 Jan 30 '13 at 23:22
  • @user1924104 answer edited. Also, there are more things you can optimize in your code, but that's out of the scope of the question. – Luiggi Mendoza Jan 30 '13 at 23:37
  • Thanks, but i still get `cannot find symbol` for directory in the copyFile – user1924104 Jan 30 '13 at 23:40
  • @user1924104 code fixed. Next time **don't copy n' paste** the code like if was yours, you **must analyze it** and then **adapt it to your needs**. Also, as BalusC pointed in his comment, you should not use the WEB-INF folder to store the user files. – Luiggi Mendoza Jan 31 '13 at 02:24
  • OK thanks, sorry i am still new to this !, also you say not to use the web-inf to store the uploads, where would be a more suitable place to store them ? i need to access them later on – user1924104 Jan 31 '13 at 16:24
  • i have tried to edit the code now but still getting a few small errors, would it be possible to take a look and suggest where i am going wrong ? – user1924104 Jan 31 '13 at 16:42