如何从sql server检索图像

时间:2016-08-01 19:17:12

标签: java sql-server mime

我已将图像存储在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中 这是插入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();
        }


}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

使用以下代码将图像转换为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;