我读了很多页,但我敢肯定,我在某处犯了一些错误,我不能像它应该的那样简单地上传文件。
首先,我在带有 Netbeans 7 和 JDK 1.7 的 Glassfish 3.1 上使用 JSF2.0、Primefaces 3.2 和 JPA2 进行开发。
接下来我必须说的是,我想将此代码插入到一个接口中,该接口将从许多其他类扩展而来,并且应该将文件存储在文件系统上的许多文件夹中!所以现在我将报告我写的内容,请告诉我问题出在哪里!
这是 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>D:/Cyborg/</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
包含 p:uploadFile 的页面还包含许多其他表单的字段,我将仅复制我认为您感兴趣的内容:
...
<h:form method="POST">
...
<h:outputLabel for="uploadFile" value="#{bundle.LabelUploadFile}" />
<p:fileUpload value="#{progettiController.uploadFile}" mode="simple" />
...
<h:commandLink action="#{progettiController.create}" value="#{bundle.SaveLink}" />
...
这是AbstractController接口中的代码:
protected UploadedFile uploadFile;
public void setUploadFile(UploadedFile uploadFile) {
this.uploadFile=uploadFile;
}
public UploadedFile getUploadFile() {
return uploadFile;
}
最后将方法 Create 放入 ProgettiController:
public String create() {
try {
getFacade().create(current);
System.out.println("Message: ProgettiController: Create: new row created successfully!");
try {
current=getFacade().findLast();
String ext=uploadFile.getFileName();
System.out.println("Message: ProgettiController: Create: FileName="+ext);
ext=ext.substring(ext.lastIndexOf("."),ext.length());
System.out.println("Messaggio: ProgettiController: ext="+ext);
current.setNomeFile(ext.substring(0,ext.lastIndexOf(".")));
current.setTipoFile(ext.substring(ext.lastIndexOf(".")+1,ext.length()));
getFacade().edit(current);
ext=urlFilesystem+current.getId()+ext.substring(ext.lastIndexOf(".")+1,ext.length());
System.out.println("Message: ProgettiController: Create: posizione e nome del file="+ext);
File oldFile= (File)uploadFile;
File newFile= new File(ext);
oldFile.renameTo(newFile);
} catch (Exception e) {
System.out.println("Messaggio: ProgettiController: Create: errore nel try legato al upload="+e.getMessage());
e.printStackTrace();
}
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProgettiCreated"));
recreateModel();
System.out.println("Messaggio: ProgettiController: create try");
return url+"List?faces-redirect=true";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
System.out.println("Messaggio: ProgettiController: create catch="+e.getMessage());
e.printStackTrace();
return url+"List?faces-redirect=true";
}
}
如果我尝试此代码,问题是当页面调用该方法将 null 返回到 uploadFile 中,如果我将“enctype="multipart/form-data"”添加到 h:form 标记中,则应用程序没有调用该方法!有人能帮我吗?非常感谢!