给动态指定路径——依据数据库动态生成图片

本文介绍了如何在服务器端利用数据库动态生成并存储图片,图片以其数据库ID命名,避免重名问题并方便检索。当接收到请求时,系统会检查文件夹是否存在对应ID的图片,若不存在则从数据库中生成并保存,再返回图片路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大概思路

在服务器端会有一个文件夹,假定该文件夹为map,专门用来存储图片,图片以其在数据库中的ID命名,这样的好处有二:

1、  不用担心文件夹中图片的重名问题

2、  由于和数据库中的标识保持一致

3、  便于机器检索

当有请求时,比如要在页面上显示1001.jpgAction会首先在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!");

       }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值