【问题标题】:How to upload file of p:fileUpload using command button instead of upload button如何使用命令按钮而不是上传按钮上传 p:fileUpload 的文件
【发布时间】:2013-11-28 19:34:54
【问题描述】:

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

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】:

    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>
    

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

    替代方法是迁移到 JSF 2.2 中引入的标准 JSF &lt;h:inputFile&gt; 组件。然后你可以继续使用 Ajax。

    例如

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

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

    另见:

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 2013-07-26
      • 2012-09-21
      • 2014-10-14
      • 1970-01-01
      • 2014-04-25
      相关资源
      最近更新 更多