save image file in specific directory jsf primefaces project

橙三吉。 提交于 2019-12-19 12:20:33

问题


I want to save byte[] file into a specific directory : I get it from this method :

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

and I access the byte[] with :

uploadedPicture.getContents()

I tested this link but no result

how to save it into a specific directory either inside my project or outside

thank you

*********EDIT********** here is the code whic works but sometimes I have the error :

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:


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
    }
}


来源:https://stackoverflow.com/questions/15638248/save-image-file-in-specific-directory-jsf-primefaces-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!