save image file in specific directory jsf primefac

2019-02-21 07:35发布

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条回答
一夜七次
2楼-- · 2019-02-21 08:00
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
    }
}
查看更多
登录 后发表回答