Primefaces fileupload重置ajax更新

时间:2013-07-03 12:12:29

标签: ajax jsf file-upload primefaces

我在primefaces数据表中进行多记录编辑,在记录编辑中有文件上传,当用户按下“添加”按钮时重置

jsf代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui">
    <h:head></h:head>
    <h:body>
        <h:form enctype="multipart/form-data">
            <p:dataTable var="file" value="#{fileUpload.files}" id="uploadTable">
                <p:column>
                    <p:inputText value="#{file.id}"/>
                    <p:inputText value="#{file.name}"/>
                    <p:fileUpload value="#{file.file}" mode="simple"/> 
                </p:column>
            </p:dataTable>
            <p:commandButton value="Add" action="#{fileUpload.add}" update="uploadTable" />
            <p:commandButton action="#{fileUpload.submit}" value="Submit" ajax="false" />
        </h:form>
    </h:body>
</ui:composition>

这是控制器:

@ManagedBean(name = "fileUpload")
@ViewScoped
public class DummyFileUpload implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<File> files;

    @PostConstruct
    public void init() {
        files = new ArrayList<DummyFileUpload.File>();
    }

    public void submit() {
        // submit
    }

    public void add() {
        files.add(new File());
    }

    public List<File> getFiles() {
        return files;
    }

    public void setFiles(List<File> files) {
        this.files = files;
    }

    public class File implements Serializable{

        private static final long serialVersionUID = 2685385696849425824L;
        private String id;
        private String name;
        private UploadedFile file;

        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public UploadedFile getFile() {
            return file;
        }
        public void setFile(UploadedFile file) {
            this.file = file;
        }
    }

}

当我进行ajax调用时,文件上传控件被重置,我知道这是一种正常的行为,但我在问这种情况是否有一个已知的解决方法,对于像这样的复杂业务,最佳做法是什么?

1 个答案:

答案 0 :(得分:1)

将文件上传标记更改为以下内容可以避免这种情况:

<p:fileUpload fileUploadListener="#{fileUpload.add}" mode="advanced" />

这样就不需要AddSubmit按钮以及AJAX更新,因为文件上传的高级版本将提供相同的功能。

此外,在您的DummyFileUpload bean中,您需要更改add函数:

public void add(FileUploadEvent event) {
    files.add(event.getFile());
}