使用PrimeFaces和JSF上传并保存图像

时间:2017-11-02 11:28:46

标签: jsf primefaces

你好我是JSF和primefacess的新手,我想上传一张图片并将其保存在我项目的文件夹中

当执行所有代码正确传递但当我检查保存目录时,我找不到我保存的图像。

// Java代码     私有的UploadedFile文件;

public UploadedFile getFile() {
    return file;
}



public void setFile(UploadedFile file) {
    this.file = file;
}



public void upload() {
    if(file != null) {
        try {
                FacesContext context = FacesContext.getCurrentInstance();
                ServletContext scontext = (ServletContext)context.getExternalContext().getContext();
                String rootpath = scontext.getRealPath("/");
                File fileImage=new File(rootpath+"upload\\temp\\text.png");
                InputStream inputStream=file.getInputstream();
                SaveImage(inputStream,fileImage);

                FacesMessage message = new FacesMessage(rootpath);
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        catch(IOException e) {
            e.printStackTrace();
            FacesMessage message = new FacesMessage("There was a probleme your file was not uploaded.",e.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }
}

public void SaveImage(InputStream inputStream, File ImageFile) throws IOException {
    OutputStream outputStream=new FileOutputStream(ImageFile);
    IOUtils.copy(inputStream, outputStream);
}

// XHTML代码

<h:form enctype="multipart/form-data">
    <p:growl id="messages" showDetail="true" />
    <p:fileUpload value="#{userBean.file}" mode="simple" skinSimple="true"/>
    <p:commandButton value="Submit" ajax="false" actionListener="#{userBean.upload}" />
</h:form>

2 个答案:

答案 0 :(得分:2)

可能是因为您正在运行的操作系统,并且在使用\时它无法正确识别路径:

File fileImage=new File(rootpath+"upload\\temp\\text.png");

将此行替换为:

File fileImage=new File(rootpath+"upload"+File.separator+"temp"+File.separator+"text.png");

当您在不同平台上处理文件路径时,这是一种很好的做法。

答案 1 :(得分:0)

您可以使用此方法:

您可以使用FileUploadEvent获取输入流,如:

InputStream in = event.getFile().getInputstream() ; 
public void upload(String fileName, String destination, InputStream in) {
    try {

        // write the inputStream to a FileOutputStream            
        OutputStream out = new FileOutputStream(new File(destination + "/" + fileName));
        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();
        System.err.println("New file created!");
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

}