jsf的Implementation有两个
Sun JSF Reference Implementation
和myface
?jsf 的t标签
你先要去 myfaces.apache.org 下个 jsf1.2 的实现包 myfaces-core-1.2.6-bin.zip
在下一个 tomahawk12-1.1.8-bin.zip (这个应该是最新的吧。我用的是1.1.6。这个不行的话你试试其它的)
<%@taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%>
就可以用了。
里面可以用 <t:inputFileUpload> 这个上传组件
随机命名上传(解决上传文件含中文和同名会覆盖的问题)
1.UploaderHelper.java
package com.pp.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.apache.myfaces.custom.fileupload.UploadedFile;
public class UploaderHelper {
public final static String uploadPath = "uploadFile";
public static String uploadFileToDisk(UploadedFile myFile) {
try {
long time = System.currentTimeMillis();
InputStream in = myFile.getInputStream();
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession hs = (HttpSession) ctx.getExternalContext().getSession(
true);
String directory = hs.getServletContext().getRealPath("//")
+ uploadPath;
File fileDir = new File(directory);
if (!fileDir.exists()) {
fileDir.mkdir();
}
String fileName = String.valueOf(Thread.currentThread()
.getContextClassLoader().hashCode())
+ "_"
+ time
+ myFile.getName().substring(
myFile.getName().lastIndexOf("."));
String file = hs.getServletContext().getRealPath("//") + uploadPath
+ "//" + fileName;
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(file));
byte[] buffer = new byte[1024 * 2];
int length;
while ((length = in.read(buffer, 0, buffer.length)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
return uploadPath + "/" + fileName;
// return "//" + uploadPath+"//"+ fileName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2使用
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%>
<h:form id="addid" enctype="multipart/form-data">
<x:inputFileUpload id="fileId" value="#{picBean.myfile}" storage="file" οnchange="showPic()"/>
<img id="picId" height="30 width="40" alt="显示图片" title="s"/>
picBean的add方法
private UploadedFile myfile;
// 上传图片和类型不能为空
if (myfile != null) {
String test = myfile.getContentType();
if (!test.startsWith("image/")) {
wrongpictype = "图片格式不对";
return "";
}
String path=UploaderHelper.uploadFileToDisk(myfile);
this.picnews.setTurl(path);
<h:outputLabel value="#{pnBean.wrongpictype}"></h:outputLabel>