簡體   English   中英

如何從SQL Server檢索圖像

[英]How to retrieve image from 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

}
 }

它以二進制格式存儲在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();
        }


}

在短期內,我告訴你! 首先創建表,然后添加列圖像URL並保存圖像URL,當您獲取詳細信息時也將其獲取並設置在標簽上

使用以下代碼將圖像轉換為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM