j2ee primefaces fileupload文件保存目标

时间:2010-12-05 11:12:56

标签: java file-upload primefaces

今天我遇到了PrimeFaces FileUpload的问题。它运行良好,但文件存储在JBoss的临时目录中,所以每当我重新部署应用程序或只是将源提交到svn时,我上传的所有图像都消失了。所以我想问一下,是否有办法将图像保存到战争项目的“源”目录中。

我的handleFileUpload方法:

public String getUrlBase() {
    return FacesContext.getCurrentInstance().getExternalContext().getRealPath("//upload");
}

public void handleFileUpload(FileUploadEvent event) {
        new File(getUrlBase() + "/" + album.getId()).mkdirs();
        File result = new File(getUrlBase() + "/" + album.getId() + "/" + event.getFile().getFileName());

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }

            fileOutputStream.close();
            inputStream.close();

            FacesMessage msg = new FacesMessage("Succesful",
                    event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            e.printStackTrace();
            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }

编辑:另一个问题

我的观看文件:

<h:form enctype="multipart/form-data" prependId="false">
        <p:growl id="messages" showSummary="true" showDetail="true" />
        <p:fileUpload fileUploadListener="#{photo.handleFileUpload}"
                      update="messages"  sizeLimit="1073741824"
                      multiple="true" label="choose" allowTypes="*.jpg;*.png;*.gif;"
                      description="Images" />
    </h:form>

当我将update =“messages”添加到fileUpload时,我得到了

javax.servlet.ServletException: null source

每当我尝试用fileUpload打开页面时。难道你不知道怎么摆脱它?

1 个答案:

答案 0 :(得分:1)

如果需要,您可以在web.xml中配置上传目录。

<filter>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <filter-class>
    org.primefaces.webapp.filter.FileUploadFilter
  </filter-class>
  <init-param>
    <param-name>uploadDirectory</param-name>
    <param-value>/Users/primefaces/temp</param-value>
  </init-param>
</filter>