大概思路
在服务器端会有一个文件夹,假定该文件夹为map,专门用来存储图片,图片以其在数据库中的ID命名,这样的好处有二:
1、 不用担心文件夹中图片的重名问题
2、 由于和数据库中的标识保持一致
3、 便于机器检索
当有请求时,比如要在页面上显示1001.jpg,Action会首先在map文件夹下遍历,若存在则直接将该文件的路径赋予url;否则,根据文件名1001从数据库表中生成图片1001.jpg并且放在该map文件夹下,然后经该图片路径赋予url;
实现
从数据库生成图片:
public String OutputImage()
{
try
{
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
String url = "jdbc:db2://127.0.0.1:50000/test";
Properties props = new Properties();
props.setProperty("user", "db2admin");
props.setProperty("password", "ibmdb2");
con=DriverManager.getConnection(url,props);
String sql = "SELECT pic FROM mytable WHERE picname='abc'";
Statement st2 = con.createStatement();
ResultSet rs = st2.executeQuery(sql);
rs.next();
OutputStream out=ServletActionContext.getResponse().getOutputStream();
InputStream is = rs.getBinaryStream("pic");
int c;
byte b[] = new byte[4*1024];
while ((c=is.read(b))!=-1)
{
out.write(b, 0, c);
}
System.out.print(getUrl());
out.flush();
out.close();
is.close();
st2.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return "outSuccess";
}
在map文件夹下遍历文件:
private static void doSearch(String path,String fileName){
File file = new File(path);
if(file.exists()) {
if(file.isDirectory()) {
File[] fileArray = file.listFiles();
for(File f:fileArray) {
if(f.isDirectory()) {
doSearch(f.getPath(),fileName);
} else {
if(f.getName().equals(fileName))
{
break;
}
}
}
}
} else {
System.out.println("The path had been apointed was not Exist!");
}
}