2016-08-01 127 views
0

我已經在sql server數據庫中存儲圖像。我需要取回他們並通過電子郵件發送。有沒有辦法將圖像存儲在變量中並將其發送到電子郵件正文中。如何從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 

} 
} 

它存儲在數據庫中的二進制格式 系統路徑上傳圖像代碼這裏是代碼用於插入分貝

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(); 
     } 


} 
+0

你在問什麼? SQL存儲或電子郵件附件? –

+0

您可以將JPG的數據保存到SQL表中的Base64中,或者也可以將文件保存在服務器上並將路徑保存到表中的文件中。 – Momo

+0

在關係數據庫中存儲圖像通常是一個壞主意。磁盤上的文件或像mongo這樣的nosql存儲應該會更好。你想知道什麼? – borowis

回答

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; 
1

短期內我告訴你!!!! 首先創建表,然後添加列圖像的URL和保存圖像的URL在這個和當你獲取細節獲取它也設置在標籤

+0

我無法存儲網址,因爲圖像應該上傳到數據庫,然後電子郵件應該選擇這些圖像併發送電子郵件。 –