将图像文件保存在特定目录jsf primefaces项目中

时间:2013-03-26 13:28:07

标签: file-upload jsf-2 primefaces directory

我想将byte []文件保存到特定目录中: 我从这个方法得到它:

public void setUploadedPicture(UploadedFile uploadedPicture)
{
    System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());        
    this.uploadedPicture = uploadedPicture;
}

我用:

访问byte []
uploadedPicture.getContents()

我测试了这个link但没有结果

如何将其保存到项目内部或外部的特定目录中

谢谢

** * ** * *** 修改 * ** * ** * ** * 这是代码有效,但有时我有错误:

public void setUploadedPicture(UploadedFile uploadedPicture)
{
    System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());        
    this.uploadedPicture = uploadedPicture;

    InputStream inputStr = null;
    try {
        inputStr = uploadedPicture.getInputstream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //create destination File
    String destPath = "C:\\"+uploadedPicture.getFileName();
    File destFile = new File(destPath);

    //use org.apache.commons.io.FileUtils to copy the File
    try {                    
        FileUtils.copyInputStreamToFile(inputStr, destFile);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:3)

public void handleFileUpload(FileUploadEvent event) {  

    //get uploaded file from the event
    UploadedFile uploadedFile = (UploadedFile)event.getFile();

    //create an InputStream from the uploaded file
    InputStream inputStr = null;
    try {
        inputStr = uploadedFile.getInputstream();
    } catch (IOException e) {
        //log error
    }

    //create destination File
    String destPath = "your path here";
    File destFile = new File(destPath);

    //use org.apache.commons.io.FileUtils to copy the File
    try {                    
        FileUtils.copyInputStreamToFile(inputStr, destFile);
    } catch (IOException e) {
        //log error
    }
}