RichFaces文件上传
程序员文章站
2024-03-12 19:41:02
...
Java代码:
public String uploadListener(UploadEvent event) {
String url;
UploadItem item = event.getUploadItem();
String fileName = item.getFileName();
System.out.println("fileName:"+fileName);
int a = fileName.lastIndexOf(".");
// 图片后缀
String ext = fileName.substring(a+1);
System.out.println("ext:"+ext);
SimpleDateFormat matter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
// 图片新名称
String fileNewName=matter.format(System.currentTimeMillis())+"."+ext;
System.out.println("fileNewname:"+fileNewName);
try {
String filepath = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "upload"+"/";
System.out.println("filePath:"+filepath);
File file = new File(filepath, fileName);
FileInputStream fis = new FileInputStream(item.getFile());
FileOutputStream out = new FileOutputStream(file);
int bytes = 0;
byte[] bteFile = new byte[1024];
while ((bytes = fis.read(bteFile)) != -1) {
out.write(bteFile, 0, bytes);
}
} catch (Exception e) {
}
url = "upload" + "/" +fileNewName;
System.out.println("url:"+url);
return url;
}
Java代码:
<h:form>
<h:panelGroup>
<h:outputText value="上传头像"></h:outputText>
<rich:spacer height="3" />
<rich:fileUpload fileUploadListener="#{MyBean.uploadListener}"
maxFilesQuantity="5"
autoclear="false"
addControlLabel="添加图片"
uploadControlLabel="上传"
clearAllControlLabel="清除所有"
clearControlLabel="清除"
cancelEntryControlLabel="取消"
stopControlLabel="停止"
stopEntryControlLabel="停止" noDuplicate="true"
id="upload"
>
<h:outputText value="{_KB}KB from {_KB}KB uploaded --- {mm}:{ss}" />
</rich:fileUpload>
</h:panelGroup>
</h:form>