<h:body>
<div id="main" align="center" style="width:100%;height: 100%">
<f:view>
<h:form id="catform" enctype="multipart/form-data">
<p:panel styleClass="ui-panel-titlebar" id="panel1" header="Add New Category" >
<h:panelGrid columns="3" style="border:0px" styleClass="ui-panel-content">
<h:outputText value="Parent Category:" />
<h:selectOneMenu id="parentcat" value="#{CategoryMB.selectedCatId}">
<f:selectItems value="#{CategoryMB.categories}" var="cat" itemLabel="#{cat.categoryName}" itemValue="#{CategoryMB.categoryId}" />
</h:selectOneMenu>
<p:message for="parentcat" />
<h:outputText value="Category Name:" />
<p:inputText id="catname" value="#{CategoryMB.catName}" required="true" requiredMessage="Category must requried !" />
<p:message for="catname" />
<h:outputText value="Category Logo:" />
<t:inputFileUpload storage="file" id="catImageUpload" value="#{CategoryMB.file}" style="display: inline;vertical-align: baseline;margin-bottom: 10px;"/>
<h:message for="catImageUpload" />
<h:outputText value="Description" />
<p:inputTextarea id="desc" cols="10" autoResize="false" rows="4" value="#{CategoryMB.description}"></p:inputTextarea>
<p:message for="desc" id="descmsg" />
<f:facet name="footer">
<p:commandButton value="Add Category" update="growl" action="#{CategoryMB.addCategory}" icon="ui-icon-check" />
</f:facet>
</h:panelGrid>
</p:panel>
<p:growl id="growl" showDetail="true" life="5000" />
</h:form>
</f:view>
public void UploadImage() {
System.out.println("hi");
UploadedFile myfile = getFile();
byte[] buffer = null;
File tempfile=null;
if(myfile!=null)
{
String prefix = FilenameUtils.getBaseName(myfile.getName());
String suffix = FilenameUtils.getExtension(myfile.getName());
try
{
realPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/Resources/CategoryImage");
tempfile = File.createTempFile(prefix + "_", "." + suffix, new File(realPath));
OutputStream out = new FileOutputStream(tempfile);
InputStream in = new BufferedInputStream(myfile.getInputStream());
this.catImage = tempfile.getName();
try {
buffer = new byte[64 * 1024];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
} finally {
in.close();
out.close();
}
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Successful", "Successfully added category! " + catName));
}
catch(IOException e)
{
e.printStackTrace();
}
}
答案 0 :(得分:1)
<p:commandButton>
默认发送ajax请求,不支持通过ajax上传文件。为此,您应该使用<p:fileUpload mode="advanced">
代替。
将ajax="false"
添加到<p:commandButton>
以将其关闭。
<p:commandButton ... ajax="false" />
请注意<p:fileUpload mode="simple">
也可以使用<t:inputFileUpload>
代替Tomahawk {{1}}。
无关,将上传的文件写入扩展的WAR文件夹是一个非常糟糕的想法。原因#1是,每当您重新部署WAR或甚至重新启动服务器时它们都会丢失,原因很简单,原因是它们不包含在原始WAR中。将它们存放在更永久的位置。另请参阅此相关答案:Uploaded image only available after refreshing the page。