Java实现把文件上传到MySQL数据库和下载回来

数据库代码:

CREATE TABLE IF NOT EXISTS `file`(
   `a` VARCHAR(100) NOT NULL,
   `b` LONGBLOB NULL,
   `DATE` VARCHAR(400),
   PRIMARY KEY ( `a` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Java代码:

上传:

package 测试;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class nat {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);//获取文件路径
        String path = sc.nextLine();
        File file = new File(path);
        String fileName=file.getName();
        FileInputStream inputStream = new FileInputStream(file);
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/你的数据库名","root","你的密码");//连接数据库
        String sql = "insert into file(a,b) values(?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, fileName);
        ps.setBinaryStream(2, inputStream, (int)file.length());//转换成2进制并上传
        int rows = ps.executeUpdate();
        System.out.println(rows);
        ps.close();
        con.close();
        sc.close();
//DATE
    }

}

下载文件代码:

package 测试;
import java.io.*;
import java.sql.*;
import java.util.Scanner;
class file {
    public static void main(String[] args) throws Exception {
      System.out.println("file name");
      Scanner sc = new Scanner(System.in);//获取文件名
      String filename = sc.nextLine();
        InputStream is = null;
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/你的数据库名","root", "你的数据库密码");//连接数据库
        byte[] buffer = new byte[4096];
        PreparedStatement ps = con.prepareStatement("select * from file where a=?");//查询
        ps.setString(1, filename);
        ResultSet rs = ps.executeQuery();//获取到数据库中的2进制代码
        rs.next();
        File file = new File("D:/"+filename);//
        if (!file.exists()) {//检查有没有此文件
            file.createNewFile();   	    
          }
          try (FileOutputStream outputImage = new FileOutputStream(file)) {
            Blob blob = rs.getBlob("b");   //b为数据库存放图片字段名称
    	    is = blob.getBinaryStream();    	   
    	    int size = 0; 	   //img
    	    while ((size = is.read(buffer)) != -1) {  	    //循环输出 
    	    	outputImage.write(buffer, 0, size);   	     
    	    }
        }    	       	    	
    	    System.out.println("file is ok ");
          sc.close();//ok
    }
}

更多推荐