我使用Tomcat和Apache能正常工作對我來說:
的形式必須是enctype="multipart/form-data
和web.xml
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
添加這些在XHTML文件:
<h:form enctype="multipart/form-data" id="upload">
<p:fileUpload id="fileUpload" fileUploadListener="#{uploadParcelBean.handleFileUpload}" mode="advanced"
allowTypes="/(\.|\/)(gif|jpe?g|png|bmp|pdf|doc|docx|xls|xlsx|txt)$/"
description="Select File"
label="Select File" uploadLabel="Upload" cancelLabel="Cancel"
validatorMessage="Invalid Format."
dragDropSupport="true"
multiple="true"
update="growl fileList"
disabled="false"/>
</h:form>
在bean方面,你可以處理上傳的fil ES:
public void handleFileUpload(FileUploadEvent event) {
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
//other logics
}
catch(IOException e){
e.printStackTrace();
}
和複製的方法是這樣的:
public void copyFile(String fileName, InputStream in) {
String destination="C:\\uploads\\";
try {
// write the inputStream to a FileOutputStream
File theDir = new File(destination);
if(!theDir.exists())
{
try {
theDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
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();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
「左設備上沒有空間」 – Stefan 2014-12-03 07:55:41