我使用JSF2.1和primefaces来上传文件。在我的应用程序中,我必须在创建记录时动态添加文件。但是当我使用时 我无法在保存期间编写用于上传文件的代码。我希望仅在保存时上传文件,而不是在上传期间上传。 任何人都可以帮我解决如何实现这个
public String handleFileUpload(FileUploadEvent event) throws IOException {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
UploadedFile file = event.getFile();
String prefix = FilenameUtils.getBaseName(file.getFileName());
String suffix = FilenameUtils.getExtension(file.getFileName());
String path = "C:/apache-tomcat-7.0.47/webapps/ROOT/WEB-INF/images";
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File fileToDirectory = File.createTempFile(prefix + "-", "." + suffix, new File(path));
InputStream inputStream = event.getFile().getInputstream();
String fileName = event.getFile().getFileName();
OutputStream outputStream = new FileOutputStream(fileToDirectory);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
return path+fileName;
}
我需要保存此代码,但在保存期间我无法获取事件
答案 0 :(得分:1)
advanced mode无法做到这一点。请改用simple mode。然后,您可以直接将输入值绑定到UploadedFile
属性。
E.g。
<h:form enctype="multipart/form-data">
...
<p:fileUpload mode="simple" value="#{bean.file}" />
...
<p:commandButton value="Save" action="#{bean.save}" ajax="false" />
</h:form>
与
private UploadedFile file; // +getter+setter
public void save() {
// ...
}