Java+mysql Local image upload database and download sample

  • 2020-06-03 06:21:57
  • OfStack

Make a small example of uploading a local image to the mysql database and download it to the desktop to check if the upload is successful.

The image table is created in the database to store images before writing the code.


create table image 
(id int primary key auto_increment , 
 name varchar(30) COMMENT ' The name of the ', 
 content mediumblob COMMENT ' The picture ');

The code is as follows:


package jdbc_imagetest;

import java.io.*;
import java.sql.*;
/**
 *  To upload images of local files to the database test the image Table and download to the native desktop 
 */
public class Test1 {

  private static String url="jdbc:mysql://localhost:3306/test";
  private static String user="root";
  private static String password="123456";
  private static Connection con;

  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection(url,user,password);
    shangchuan();
    xiazai();    
  }
  // Add images to the database test4 the file table 
  public static void shangchuan() throws Exception{
    String sql="insert into image(name,content) values(?,?)";
    PreparedStatement ptmt=con.prepareStatement(sql);
    ptmt.setString(1, " The beauty .jpg");
    InputStream is=null;
    is=new FileInputStream("D:\\Pictures\\3.jpg");
    ptmt.setBinaryStream(2, is,is.available());
    // Method description: PreparedStatement.setBinaryStream(int parameterIndex, InputStream x, int length)
    ptmt.execute();
    System.out.println(" Picture added successfully! ");

  }
  // Download images from the database to the desktop 
  public static void xiazai() throws Exception{
    String sql="select content from image where id=3";// I'm here 3.jpg Is the first 3 image 
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery(sql);// Give the query results to rs
    if(rs.next()){
      InputStream is=rs.getBinaryStream("fcontent");
      //.getBinaryStream():a Java input stream that delivers the database column value as a stream of uninterpreted bytes
      FileOutputStream fos=new FileOutputStream("C:\\Users\\Desktop\\ The beauty .jpg");
      byte[] buffer=new byte[1024];
      int len=0;
      while((len=is.read(buffer))!=-1){
        fos.write(buffer,0,len);// Write out the picture of the database 
      }
      System.out.println(" Download successful! Downloaded to desktop, please check ");
    }else{
      System.out.println(" The picture does not exist! ");
    }
    con.close();
  }


}

Test success


Related articles: