【问题标题】:How to retrieve image from sql server如何从 sql server 中检索图像
【发布时间】:2016-12-06 23:38:17
【问题描述】:

我已将图像存储在 sql server 数据库中。我需要获取它们并通过电子邮件发送它们。有没有办法将图像存储在变量中并在电子邮件正文中发送。

这是从系统路径上传图片的代码

public class ImageInsert {

 private static java.sql.Date getCurrentDate() {
        java.util.Date today = new java.util.Date();
        return new java.sql.Date(today.getTime());
    }
 public void insertImage() {
// declare a connection by using Connection interface 
Connection connection = null;
/* Create string of connection url within specified format with machine 
name, port number and database name. Here machine name id localhost 
and database name is Test. */
String connectionURL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=Test";
/*declare a resultSet that works as a table resulted by execute a specified 
sql query. */
ResultSet rs = null;
// Declare prepare statement.
PreparedStatement psmnt = null;
// declare FileInputStream object to store binary stream of given image.
FileInputStream fis;
try {
    // Load JDBC driver "com.mysql.jdbc.Driver"
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    /* Create a connection by using getConnection() method that takes 
    parameters of string type connection url, user name and password to 
    connect to database. */
    connection = DriverManager.getConnection(connectionURL, "sa", "$arat0ga~");
    // create a file object for image by specifying full path of image as parameter.
    File media = new File("C:/HBD.jpg");
    /* prepareStatement() is used for create statement object that is 
    used for sending sql statements to the specified database. */
    psmnt = connection.prepareStatement("insert into WishEmail(filename, media, date ) " + "values(?,?,?)");
    psmnt.setString(1, "Happy Birthday");
    psmnt.setDate(3, getCurrentDate());
    fis = new FileInputStream(media);
    psmnt.setBinaryStream(2, (InputStream) fis, (int)(media.length()));
    /* executeUpdate() method execute specified sql query. Here this query 
    insert data and image from specified address. */
    int s = psmnt.executeUpdate();
    if (s > 0) {
        System.out.println("Uploaded successfully !");
    } else {
        System.out.println("unsucessfull to upload image.");
    }
}
// catch if found any exception during rum time.
catch (Exception ex) {
    System.out.println("Found some error : " + ex);
} finally {
    //finally block used to close resources
      try{
         if(psmnt!=null)
            connection.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(connection!=null)
            connection.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try

}
 }

它以二进制格式存储在db中 这是插入数据库的代码

public class DB {

public DB() {}

public Connection dbConnect(String db_connect_string,
   String db_userid, String db_password)
{
        try
        {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                Connection conn = DriverManager.getConnection(
                  db_connect_string, db_userid, db_password);

                System.out.println("connected");
                return conn;

        }
        catch (Exception e)
        {
                e.printStackTrace();
                return null;
        }
}

public void insertImage(Connection conn,String img)
{
        int len;
        String query;
        PreparedStatement pstmt;

        try
        {
                File file = new File(img);
                FileInputStream fis = new FileInputStream(file);
                len = (int)file.length();

                query = ("insert into WishEmail VALUES(?,?,?)");
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1,file.getName());
                pstmt.setInt(2, len);

                // Method used to insert a stream of bytes
                pstmt.setBinaryStream(3, fis, len); 
                pstmt.executeUpdate();

        }
        catch (Exception e)
        {
                e.printStackTrace();
        }
}

public void getImageData(Connection conn)
{

         byte[] fileBytes;
         String query;
         try
         {
                 query = "select image from WishEmail";
                 Statement state = conn.createStatement();
                 ResultSet rs = state.executeQuery(query);
                 if (rs.next())
                {
                          fileBytes = rs.getBytes(1);
                          OutputStream targetFile=  
                          new FileOutputStream(
                               "C:/DEF.jpg");

                          targetFile.write(fileBytes);

                          targetFile.close();
                }        

         }
         catch (Exception e)
         {
                 e.printStackTrace();
         }
}

这是发送电子邮件的代码

public class Mail {



public void sendEmail() throws IOException
{

    GetPropsValue props = new GetPropsValue();
    props.getPropValues();
    String replyTo= props.toAddress1;
    String mailFrom = props.fromAddress1;
    String smtpHost = props.smtpHost1;
    //Get the session object  
      Properties properties = System.getProperties(); 

      properties.setProperty("mail.smtp.host", smtpHost);
      properties.setProperty("replyTo", replyTo); 
      properties.setProperty("mailFrom",mailFrom); 
      Session session = Session.getDefaultInstance(properties);  

      generateAndSendEmail(
                session,
                replyTo,
                mailFrom,
                "Email for Birthday Wishes",
                "Greetings, <br><br>Happy Birthday.");

}

public static void generateAndSendEmail(Session session, String toEmail,String mailFrom, String subject, String body) { 

    //compose the message  
      try{  
          System.out.println("\n ===> generateAndSendEmail() starts..");
          MimeMessage mime1 = new MimeMessage(session);
          mime1.addHeader("Content-type", "text/HTML; charset=UTF-8");
            mime1.addHeader("format", "flowed");
            mime1.addHeader("Content-Transfer-Encoding", "8bit");
            mime1.setFrom(new InternetAddress(mailFrom,toEmail));
            mime1.setSubject(subject, "UTF-8");
            mime1.setSentDate(new Date());
            mime1.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail, false));
         // Create the message body part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(body, "text/html");

            // Create a multipart message for attachment
            Multipart multipart = new MimeMultipart();

            // Set text message part
            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

         // Valid file location
            String filename = "C:/ABC.jpg";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            // Trick is to add the content-id header here
            messageBodyPart.setHeader("Content-ID", "image_id");
            multipart.addBodyPart(messageBodyPart);

            System.out.println("\n ===> third part for displaying image in the email body..");
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("<br><h3>Happy Birthday</h3>"
                    + "<img src='cid:image_id'>", "text/html");
            multipart.addBodyPart(messageBodyPart);
            mime1.setContent(multipart);
            messageBodyPart.setContent("<br><h3>Regards</h3>", "text/html");

            System.out.println("\n ===> Finally Send message..");

            // Finally Send message
            Transport.send(mime1);

            System.out
                    .println("\n ===> Email Sent Successfully With Image Attachment. Check your email now..");
            System.out.println("\n ===> generateAndSendEmail() ends..");

        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


}

【问题讨论】:

  • 你在问什么? SQL 存储或电子邮件附件?
  • 可以将JPG的数据保存到SQL表中的Base64中,也可以将文件保存在服务器上,并将文件的路径保存在表中。
  • 在关系数据库中存储图像通常是个坏主意。磁盘上的文件或像mongo这样的nosql存储应该更好。你到底想知道什么?
  • 我需要将电子邮件和出生日期存储在数据库中,然后需要发送带有祝福他们生日的图片的电子邮件。图片应该在数据库中。
  • 不知道为什么如此坚持图像必须存储在 sql 中。正如一些人已经提到的,这通常不是一个好方法。也许 FILESTREAM 是一种选择?如果将图像存储在 varbinary(max) 列中,则必须首先将字节具体化为文件,然后将其附加到电子邮件中。

标签: java sql-server mime


【解决方案1】:

使用以下代码将图像转换为 BASE64 字符串。

   byte[] encodedBytes = null;
      String contents = "";
      Scanner scanner = null;
      StringBuilder text = new StringBuilder();
      String NL = System.getProperty("line.separator");
        try {
            encodedBytes = new Base64().encode(FileUtils.readFileToByteArray(new File(fFileName)));
            contents = new String(encodedBytes);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
        }
        return "data:image/png;base64,"+contents;

【讨论】:

    【解决方案2】:

    短期内我告诉你!!!! 首先创建表,然后添加列图像 url 并在此保存图像 url,当您获取详细信息时,也获取它并在标签上设置

    【讨论】:

    • 我无法存储 url,因为图像应该上传到数据库,然后电子邮件应该选择这些图像并发送电子邮件。
    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2014-08-22
    • 2012-03-30
    • 2013-07-25
    • 1970-01-01
    • 2011-01-26
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多