我想上传一张带有 PrimeFaces 和 jsf 的图片。图像没有上传,即使 PrimeFaces 标签看起来不错,也验证了图像的大小和类型。
我的 web.xml 配置
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>5120000</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>D:\tmp</param-value>
</init-param>
</filter>
我的 xhtml 中的 PrimeFaces 代码
<p:fileUpload fileUploadListener="#{itemBean.handleFileUpload}" mode="advanced" dragDropSupport="false"
update="messages" sizeLimit="10000000" fileLimit="1" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:growl id="messages" showDetail="true"/>
ItemBean 代码
private String destination="D:\\tempt\\";
public void handleFileUpload(FileUploadEvent event) {
System.out.println("going to file upload");
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
// Do what you want with the file
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
......................