【问题标题】:store image in mysql and retrieve it将图像存储在mysql中并检索它
【发布时间】:2012-05-05 15:26:31
【问题描述】:

我正在用 jsp&servlet 创建一个网站

我想问一下:

将图像存储在数据库(mysql)中并检索它的最佳方法是什么

将其用作个人资料的图片

我该怎么做?

提前谢谢大家。

【问题讨论】:

    标签: java mysql image jsp servlets


    【解决方案1】:

    两种常见的解决方案:

    • 直接在数据库中的一个字节字段中

    • 在磁盘上,路径存储在数据库中(我个人喜欢使用文件的 SHA1 作为名称,所以我不能拥有两次相同的文件,路径为 a/b/cdef 如果SHA1 是 abcdef)

    两种解决方案都运行良好。第一个解决方案的优点是只有一个文件要备份、启用回滚等等。第二种可能更自然,因为磁盘文件系统是用来存储文件的。

    【讨论】:

    • 我该如何实施第二种解决方案?
    • 你要接收图片(google "upload servlet"),找到文件内容的SHA1(google "MessageDigest SHA1 java"),从这个SHA1推导出一个本地路径,把文件存放在磁盘,将本地路径存储在数据库中。
    【解决方案2】:

    将图像保存在服务器上的文件夹中。 将图像路径保存在 db 中。 在显示时从数据库中获取图像路径并检索图像。

    【讨论】:

      【解决方案3】:

      将图像存储在数据库中。

          import java.sql.*;
          import java.io.*;
      
          public class insertImage{
           public static void main(String[] args) {
            System.out.println("Insert Image Example!");
            String driverName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/";;
            String dbName = "databasename";
            String userName = "root";
            String password = "root";
            Connection con = null;
      
            try{
             Class.forName(driverName);
             con = DriverManager.getConnection(url+dbName,userName,password);
             Statement st = con.createStatement();
             File imgfile = new File("images.jpg");
             FileInputStream fin = new FileInputStream(imgfile);
             PreparedStatement pre = con.prepareStatement("insert into Tablename values(?)");
             pre.setBinaryStream(3,fin,(int)imgfile.length());
             pre.executeUpdate();
             System.out.println("Inserting Successfully!");
             pre.close();
             con.close(); 
           }
           catch (Exception e){
            System.out.println(e.getMessage());
           }
          }
         }
      

      使用 Servlet 从数据库中检索图像 http://www.roseindia.net/servlets/retreiveimage.shtml

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 2018-07-07
        相关资源
        最近更新 更多