如何使用命令按钮而不是上传按钮来上传p:fileUpload的文件

问题描述 投票:2回答:1

我使用JSF2.1连同质数来上传文件。在我的应用程序中,我必须在创建记录时动态添加文件。但是当我使用我无法编写用于在保存期间上传文件的代码。我希望仅在单击保存时上传文件,而不要在上传过程中上传。谁能帮我实现这个]

public String handleFileUpload(FileUploadEvent event) throws IOException {  
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);  
    UploadedFile file = event.getFile();

    String prefix = FilenameUtils.getBaseName(file.getFileName());
    String suffix = FilenameUtils.getExtension(file.getFileName());


    String path = "C:/apache-tomcat-7.0.47/webapps/ROOT/WEB-INF/images";

     ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();


    File fileToDirectory = File.createTempFile(prefix + "-", "." + suffix, new File(path));

    InputStream inputStream = event.getFile().getInputstream();
    String fileName = event.getFile().getFileName();

    OutputStream outputStream = new FileOutputStream(fileToDirectory);

    byte[] buffer = new byte[1024];

    int length;
    //copy the file content in bytes 
    while ((length = inputStream.read(buffer)) > 0){

        outputStream.write(buffer, 0, length);

    }

    inputStream.close();
    outputStream.close();
    return path+fileName;


}

我需要保存此代码,但在保存期间无法获取事件

file-upload jsf-2 primefaces commandbutton
1个回答
1
投票
auto mode无法做到。请改用basic mode。然后,您可以将输入值直接绑定到UploadedFile属性。这仅需要禁用Ajax。

例如

<h:form enctype="multipart/form-data"> ... <p:fileUpload mode="simple" value="#{bean.file}" /> ... <p:commandButton value="Save" action="#{bean.save}" ajax="false" /> </h:form>

with

private UploadedFile file; // +getter+setter public void save() { try (InputStream input = file.getInputStream()) { // ... } }

替代方法是迁移到JSF 2.2中引入的标准JSF <h:inputFile>组件。然后,您可以继续使用Ajax。

例如

<h:form enctype="multipart/form-data"> ... <h:inputFile value="#{bean.file}" /> ... <p:commandButton value="Save" action="#{bean.save}" /> </h:form>

with

private Part file; // +getter+setter public void save() { try (InputStream input = file.getInputStream()) { // ... } }

另请参见:

© www.soinside.com 2019 - 2024. All rights reserved.