[英]Load and display images in JSF
我将图像保存到系统的文件夹中。 这些已成功上传。 然后我将图像名称保存到数据库中。 现在,为了显示图像,我正在获取文件的名称,然后尝试显示它,但是它不起作用。 代码如下
用于上传目的
<h:outputLabel value="Select Image"></h:outputLabel>
<x:inputFileUpload id="file"
value="#{schoolMember.image}"
required="true" size="40" />
<h:outputText></h:outputText>
<h:commandButton value="Save Details"
action="#{schoolMember.saveMember}">
</h:commandButton>
Java类中使用的方法
public void saveMember()
{
File savedFileName;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String dirPath = "B:\\ImagesUpload\\";
InputStream fileContent = null;
try {
fileContent = image.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String uploadFileName = trimFilePath(image.getName());
String nameofFile=timeStamp + uploadFileName;
this.setFileName(nameofFile);
savedFileName = new File(dirPath +nameofFile);
System.out.println(nameofFile);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(savedFileName));
} catch (FileNotFoundException e) {
}
byte[] buffer = new byte[1024];
int len;
try {
while ((len = fileContent.read(buffer)) >= 0) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
}
try {
fileContent.close();
bos.close();
} catch (IOException e) {
}
SchoolMemberDao dao=new SchoolMemberDao();
dao.saveSchoolMember(this);
this.clearAll();
}
一切正常,现在我从数据库中获取文件名,如下所示
public void memberByEmailEdit() throws IOException
{
String dirPath = "B:\\ImagesUpload\\";
SchoolMemberDao dao=new SchoolMemberDao();
List<SchoolMember> list=dao.memberByEmail(memberEmail);
this.memberId=list.get(0).memberId;
this.fileName=list.get(0).fileName;
String uploadFileName = trimFilePath(list.get(0).fileName);
System.out.println(uploadFileName);
this.setImageFileName(uploadFileName);
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/faces/views/SchoolMembers/Principal/editProfile.xhtml");
}
我使用查询获取这些值的方法是
public List<SchoolMember> memberByEmail(String mEmail)
{
Transaction trans=null;
Session session=HiberUtil.getSessionFactory().openSession();
try{
trans=session.beginTransaction();
String queryString="from SchoolMember s where s.memberEmail = :id and memberType = 'principal'";
Query query=session.createQuery(queryString);
query.setString("id", mEmail);
List<SchoolMember> list=query.list();
if(list.size()>0)
{
return list;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
现在在这里如下所示,我给的URL来获取图像,但它不显示该图像
<h:graphicImage height="100"
width="100"
url="B:\\ImagesUpload\\#{schoolMember.imageFileName}">
</h:graphicImage>
您的Web应用程序已部署在服务器上。 应用程序仅以其自身资源已知。 将图像上传到Web应用程序文件夹而不是B:/ ImagesUpload,例如:resouces resouces/images/
不是尝试这样做
Web服务器正在查找图像文件,例如: http://localhost:8080/B:/UploadedImages/xxx.jpg
,当然它不能完成。
例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.