因为手头有个项目要上传文件,用的是Jsf,就稍微研究了一下。一开始发现哎呀primefaces有现成的上传组件嘛,太简单了,照着官方的demo做,失败啊有没有。
在配置过滤器的时候让我配了个什么保存路径,用相对路径无论如何都说找不到什么什么,然后改成绝对路径,好了,没报错了,可是,文件呢,我上传的文件呢。后来经过思考终于悟出来,那个过滤器保存的文件时临时的,或者文件只在内存里,我们要在受管bean里自己进行保存操作。下面是我的程序。
受管bean是这样的:
@ManagedBean
@RequestScoped
public class UploadMyFile {
@ManagedProperty(value = "#{user.admin}")
private Administrator admin;
private UploadedFile fileUpload;
private String fileName;
//这里应用程序路径是可以改的,方案再令一篇博客里《jsp中获得应用程序相关路径》
private String appPath = "F:/NetBeansPro/Yinke3.1/build/web/";
/** Creates a new instance of UploadMyFile */
public UploadMyFile() {
}
public String saveFile() throws IOException {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Random r = new Random();
String adminPath = appPath + "uploadFiles/" + admin.getAdUsername();
File adminFilePath = new File(adminPath);
if (!adminFilePath.isDirectory()) {
adminFilePath.mkdir();
}
String fileType = fileUpload.getFileName().substring(fileUpload.getFileName().lastIndexOf("."));
fileName = "uploadFiles/" + admin.getAdUsername() + "/" + df.format(new java.util.Date()) + r.nextInt(10) + r.nextInt(10) + r.nextInt(10) + fileType;
InputStream is = fileUpload.getInputstream();
File dir = new File(appPath + fileName);
OutputStream fout = new FileOutputStream(dir);
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
fout.write(b, 0, len);
}
fout.close();
is.close();
return "uploadMyFile?faces-redirect=true&file=" + fileName;
}
public void setAdmin(Administrator admin) {
this.admin = admin;
}
public UploadedFile getFileUpload() {
return fileUpload;
}
public void setFileUpload(UploadedFile fileUpload) {
this.fileUpload = fileUpload;
}
}
页面代码是那样的:
<h:body>
<c:if test="#{empty param.file}">
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{uploadMyFile.fileUpload}" mode="simple" allowTypes="*.jpg;*.png"/><h:commandButton value="上传" action="#{uploadMyFile.saveFile}"/>
</h:form>
</c:if>
<c:if test="#{!empty param.file}">
<script type="text/javascript">
parent.document.pageForm.myfile.value='#{param.file}';
</script>
文件上传成功!
</c:if>
</h:body>
页面上一个文件框跟受管Bean中的fileUpload属性绑定,点击上传按钮后将文件保存起来,本来保存操作也比较简单啦,我这边写这么多事一个是单独给管理员创建目录,再一个文件名也是随机生成的,保存完了再回到上传的页面,然后显示文件上传成功,然后那段js代码是因为这个上传的页面其实是被作为一个iframe,上传成功以后把文件目录告诉给父页面的表单,原本我是把上传框跟其他输入框做在同一个表单中的,但是带来的后果是其他输入框的值乱码,花了一天没解决,就只想到这个方案,如果哪个哥哥有好方案,一定要告诉我哦。