文件上传不起作用 - Primefaces JSF

时间:2013-06-26 22:32:11

标签: jsf primefaces

我有一个项目在三个月前完美运行,只是打开它,现在我无法让文件上传工作,我不确定问题是什么,任何人有任何想法?

文件上传,触发允许用户选择文件的上传窗口,但从那时起没有任何反应,它应该向用户显示一条消息,说明是否成功,这些都没有出现

这是JSF页面:

  <p:fileUpload widgetVar="upload" id="upload" fileUploadListener="#{fileUploadController.handleFileUpload}"
                                  mode="advanced" 
                                  multiple="false" 
                                  update="messages Nav upload fileDirectoryViewer"
                                  label="Select File"
                                  sizeLimit="30720000"  
                                  allowTypes="/(\.|\/)(gif|jpe?g|png|doc|txt|pdf|html)$/"
                                  auto="true"
                                  disabled="#{fileUploadController.uploadComplete}"
                                  /> 

这是java代码:

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.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.primefaces.event.FileUploadEvent;

@ViewScoped
@ManagedBean(name = "fileUploadController")
public class FileUploadController {
//manages all the file upload

    public boolean isUploadComplete() { //to enable the next button once finished
        return uploadComplete;
    }

    public void setUploadComplete(boolean uploadComplete) {
        this.uploadComplete = uploadComplete;
    }

    public boolean isUploadComplete2() {
        //to disable the file upload button, this will stop users uploading multiple files and over writing them as only the last file uploaded will be used
        return uploadComplete;
    }

    public void setUploadComplete2(boolean uploadComplete) {
        this.uploadComplete = uploadComplete;
    }
    /*
     public void handleFileUpload(FileUploadEvent event) {
     System.out.println("called");
     FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
     FacesContext.getCurrentInstance().addMessage(null, msg);
     }
     }
     */
    //
    //Strings for fileUpload
    //oadProp() 
    //public String fileList = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/Directory Files/directoryFiles.txt"; //
    private Properties configProp = new Properties();

    @PostConstruct
    //System.out.println(destinationPDF);
    //System.out.println(destination);
// Get the username from the login page, this is used to create a folder for each user
    public void loadProp() { //loads the values from the properties fil
        System.out.println("Loading properties");
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //points to a properties file, this will load up destinations instead of having to declare them here
        try {
            configProp.load(in);
            System.out.println(configProp.getProperty("destinationPDF"));//testing to ensure correct variables are loaded
            System.out.println(configProp.getProperty("destination"));//testing to ensure correct variables are loaded
            System.out.println(configProp.getProperty("fileList"));//testing to ensure correct variables are loaded
        } catch (IOException e) {
            e.printStackTrace();
        }
        destination = configProp.getProperty("destination");//Assigning the values to a variable 
        destinationPDF = configProp.getProperty("destinationPDF");//Assigning the values to a variable 
        fileList = configProp.getProperty("fileList");//Assigning the values to a variable 

        System.out.println("called get username");
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();//retreives the username from the login page, this is used throughout the application
        //username = "cam01342"; //test
        System.out.println(username);


    }
    //String destinationPDF = configProp.getProperty("destinationPDF"); Always makes a null no idea why yet
    public String destinationPDF; // = configProp.getProperty("destinationPDF");
    public String destination;// = configProp.getProperty("destination");
    private String username;
    public String fileList;
    //public static String destination = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/uploaded/"; // main location for uploads//TORNADO ONLY //"D:/My Documents/NetBeansProjects/printing~subversion/fileupload/uploaded/"; // USE ON PREDATOR ONLY 
    public static String NewDestination;
    public static String UploadedfileName;
    public static String CompletefileName;
    //
    //Strings for file copy
    //
    //private String destinationPDF = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/"; //USE ON TORNADO//"D:/My Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/";//USE ON PREDATOR    
    private String NewdestinationPDF;
    public static String PdfLocationViewable;
    private boolean uploadComplete;
    private boolean uploadComplete2;

    //
    public void File() {
        System.out.println("File");
        File theFile = new File(destination + username); // will create a sub folder for each user 
        theFile.mkdirs();
        System.out.println("Completed File");

    }

    public File getDirectory(String destination, String username) {
        System.out.println("called get directory");//testing
        System.out.println(destination);
        // currently not working, is not calling the username or destination
        //set the user directory from the destination and the logged user name
        File directory = new File(destination, username);
        //check if the location exists
        if (!directory.exists()) {
            //Creates folder if it does not already exists
            try {
                directory.mkdir();
            } catch (SecurityException secEx) {
                secEx.printStackTrace(System.out);
                directory = null;
            }
        }
        return directory;
    }

    public void handleFileUpload(FileUploadEvent event) {
        //System.out.println("DesintationPDF : " + destinationPDF);
        System.out.println("called handle file");
        System.out.println("Destination is : " + destination);

        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); //Displays to user on the webpage using AJAX
        FacesContext.getCurrentInstance().addMessage(null, msg);


        try {
            System.out.println("Upload complete value before copy file " + uploadComplete);
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());


        } catch (IOException e) {
//handle the exception
            e.printStackTrace();
        }

    }

    public void copyFile(String fileName, InputStream in) throws IOException {
        System.out.println("CopyFile");
        try {

            uploadComplete = true; //enables the next button
            uploadComplete2 = false; // to disable the fileupload button
            System.out.println("destination is " + destination);

            System.out.println("upload complete value is : " + uploadComplete);//checkin the value to see if correct
//creates a folder for each user if one does not already exsist, if it does it will use that
//destination = "D:/My Documents/NetBeansProjects/printing~subversion/fileupload/uploaded/";  //for use when on PREDATOR
            // destination = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/"; // main location for uploads (CHANGE THIS WHEN USING PREDATOR)
            File theFile = new File(configProp.getProperty("destination") + "/" + username);
            theFile.mkdirs();// will create a sub folder for each user (currently does not work, below hopefully is a solution) (DOES NOW WORK)
            System.out.println("Completed Creation of folder");
            NewDestination = destination + username + "/";
            System.out.println(NewDestination);//testing


            //Create copy destination
            //creation of directory to use from inside the web app (Needed to display a pdf in the page
            System.out.println("Now in copying of file proccess");
            // destinationPDF = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/"; // write the inputStream to a FileOutputStream
            File theFilePDF = new File(configProp.getProperty("destinationPDF") + "/" + username);
            theFilePDF.mkdirs();// will create a sub folder for each user 
            System.out.println("Completed Creation of folder for copy of PDF");
            NewdestinationPDF = configProp.getProperty("destinationPDF") + username + "/";
            System.out.println(NewdestinationPDF);
            System.out.println("End of copying file creation");




// write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(NewDestination + fileName)); // cannot find path when adding username atm
            System.out.println("Called CopyFile"); //testing
            System.out.println(NewDestination + fileName);
            UploadedfileName = fileName;
            CompletefileName = NewDestination + UploadedfileName;
            //Will need to take the uploadfileName and If it is a doc file onvert it
            System.out.println("CompletefileName is: " + CompletefileName);//testing, will pass this value to convertPDF if doc file, This is required.
            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!");//testing
            System.out.println("Completed file name is : " + CompletefileName); //testing as currently gettng a null 


// Now copies the file from one location to another, to display this on the PDF page
            System.out.println("Copying is now happening");
            PdfLocationViewable = "../resources/pdf/" + username + "/" + UploadedfileName; //Must be in this format
            System.out.println(PdfLocationViewable);
            File source = new File(NewDestination);
            File desc = new File(NewdestinationPDF);
            {
                FileUtils.copyDirectory(source, desc);
            }

            // add if statement here to detect if uploaded file is a doc file, If so convert it to pdf, else do nothing
            System.out.println("Determine if a doc file is uploaded");
            if (fileName.endsWith(".doc")) {
                System.out.println("doc file");
                PDFConversion Conversion = new PDFConversion();
                Conversion.Conversion(CompletefileName);
            } else {
                System.out.println("not a doc file uploaded");
            }

        } catch (IOException e) {
            e.printStackTrace();
            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }


    }

    public String PdfLocationViewable() {
        System.out.println(PdfLocationViewable);//testing to make sure it is called
        return PdfLocationViewable;
    }

    public String PdfLocationIframe() {
        System.out.println(PdfLocationViewable);
        return PdfLocationViewable;
    }
    /**
     * public String uploadedFilesIframe() { System.out.println(fileList);
     * return fileList; }
     *
     * String newLine = System.getProperty("line.separator"); // puts each
     * result onto a new line
     *
     * public String FilesInFolder() throws IOException { FileWriter fw = new
     * FileWriter(fileList); StringWriter sw = new StringWriter();
     *
     * // Will list all files in the directory, want to create a feature on the
     * page that can display this to the user
     *
     * String path = NewDestination; System.out.println("Starting searching
     * files in directory"); // making sure it is called String files; File
     * folder = new File(path); File[] listOfFiles = folder.listFiles();
     *
     * for (int i = 0; i < listOfFiles.length; i++) {
     *
     * if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName();
     * sw.write(files + newLine);
     *
     * System.out.println(files); } } System.out.println("Saved list of files to
     * " + fileList); fw.write(sw.toString()); fw.close(); return
     * "/GUI/FilesUploaded.xhtml"; }
     */
}

控制台没有错误或任何内容

INFO:   D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/
INFO:   D:/Documents/NetBeansProjects/printing~subversion/fileupload/build/web/resources/Directory Files/directoryFiles.txt
INFO:   called get username
INFO:   null

它似乎没有从public void loadProp()转到上传文件的部分

任何想法?

让这个重新上线真是太棒了,从上次使用它以来唯一改变的是我现在使用netbeans 7.3.1,其中最后一次是7.2 ....

由于

2 个答案:

答案 0 :(得分:1)

这是您需要的答案tutorial use p:fileupload

答案 1 :(得分:-1)

从fileUpload标记中删除ID属性,然后尝试。