Java上传下载图片

来源:互联网 发布:linux 多进程读写文件 编辑:程序博客网 时间:2024/06/05 19:16

做一个将本地图片上传到mysql数据库的小实例,顺便也下载下来到桌面检测是否上传成功。

在写代码之前得先在数据库中建立image表,用来存储图片。

create table image 
-> (id int primary key auto_increment , 
-> name varchar(30) COMMENT '名称', 
-> content mediumblob COMMENT '图片');

下面直接上代码:

package jdbc_imagetest;import java.io.*;import java.sql.*;/** * 将本地文件的图片传到数据库的test的image表中并下载到本机桌面 */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();           }    //添加图片到数据库test4的file表    public static void shangchuan() throws Exception{        String sql="insert into image(name,content) values(?,?)";        PreparedStatement ptmt=con.prepareStatement(sql);        ptmt.setString(1, "美女.jpg");        InputStream is=null;        is=new FileInputStream("D:\\Pictures\\3.jpg");        ptmt.setBinaryStream(2, is,is.available());        //方法说明:PreparedStatement.setBinaryStream(int parameterIndex, InputStream x, int length)        ptmt.execute();        System.out.println("图片添加成功!");    }    //从数据库中把图片下载至桌面    public static void xiazai() throws  Exception{        String sql="select content from image where id=3";//在我这里3.jpg是第三张图片        Statement stmt=con.createStatement();        ResultSet rs=stmt.executeQuery(sql);//将查询结果给rs        if(rs.next()){            InputStream is=rs.getBinaryStream("content");            //.getBinaryStream():a Java input stream that delivers the database column value as a stream of uninterpreted bytes            FileOutputStream fos=new FileOutputStream("C:\\Users\\Desktop\\美女.jpg");            byte[] buffer=new byte[1024];            int len=0;            while((len=is.read(buffer))!=-1){                fos.write(buffer,0,len);//将数据库的图片写出            }            System.out.println("下载成功!已下载至桌面,请查看");        }else{            System.out.println("图片不存在!");        }        con.close();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

测试成功

原创粉丝点击