将本地文件保存至数据库中以及从数据库中读出保存至本地

一、将本地文件存储至数据表

思路:

1、读取本地文件: File file = new File(filePath);

2、将本地文件转换成字节数组

3、将字节数据保存在数据表中,数据表字段类型为Blob

代码示例:

注入数据源:

    /**
     * 注入数据源
     * */
    public JdbcTemplate getJdbcTemplate(){
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/exe?characterEncoding=utf-8&useSSL=true&&serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

 将文件转换为字节数组:

   /**
     * 将文件转成byte数组
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] getFileByte(File file) throws Exception{
        byte[] fileBytes=null;
        InputStream is = null;
        ByteArrayOutputStream os=null;
        try{
            is=new BufferedInputStream(new FileInputStream(file));
            os = new ByteArrayOutputStream();
            byte[] bt = new byte[1024];
            int i = 0;
            while ((i = is.read(bt, 0, bt.length)) != -1) {
                os.write(bt, 0, bt.length);
            }
            fileBytes=os.toByteArray();
        }finally{
            is.close();
            os.close();
        }
        return fileBytes;
    }

使用Junit进行测试: 

    /**
     * 将本地文件存储至数据库Blob
     * */
    @Test
    public void saveFile(){
        //本地文件路径
        String filePath = "C:\\Users\\HDN\\Desktop\\P0005204-朱佳佳.bmp";
        //读取本地文件
        File file = new File(filePath);
        String sql = "insert into file(id,name,file) value(?,?,?)";
        try {
            //将本地文件转换成字节数组保存在数据表中,数据表中该字段类型为blob
            byte[] bytes = getFileByte(file);
            this.getJdbcTemplate().update(sql, UUID.randomUUID().toString().replace("-",""),"图片1",bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

二、将文件从数据表中读出并保存至本地

思路:

1、从数据表中读取保存文件的Blob字段值

2、将Blob字段值转换成字节数组

3、设置存储在本地的路径和文件名:File file = new File(filePath,fileName);

4、写入到本地

代码示例:

注入数据源:

    /**
     * 注入数据源
     * */
    public JdbcTemplate getJdbcTemplate(){
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/exe?characterEncoding=utf-8&useSSL=true&&serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

将Blob转换为byte[]: 

    /**
    * 将Blob数据转化为byte[]
    * @param blob
    * @return byte[]
    * */
    public byte[] blobToBytes(Blob blob) {
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(blob.getBinaryStream());
            byte[] bytes = new byte[(int) blob.length()];
            int len = bytes.length;
            int offset = 0;
            int read = 0;
            while (offset < len
                    && (read = is.read(bytes, offset, len - offset)) >= 0) {
                offset += read;
            }
            return bytes;
        } catch (Exception e) {
            return null;
        } finally {
            try {
                is.close();
                is = null;
            } catch (IOException e) {
                return null;
            }
        }
    }

写入文件数据到指定文件: 

    /**
     * 写入文件数据到指定文件
     * @param fileData
     * @param file
     */
    public static void writeFile(byte[] fileData, File file){
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(file.getAbsoluteFile());
            fos.write(fileData);
            fos.flush();
        }catch (Exception e){

        }finally{
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用Junit进行测试:

    /**
     * 从数据库中取Blob数据,并将其转化为文件保存至本地目录中
     * */
    @Test
    public void getFile(){
        String sql = "select file from file where  id= '05206705c4394f34ae9bc7253443ff68'";
        List<byte[]> list = this.getJdbcTemplate().query(sql, new Object[]{}, new RowMapper<byte[]>() {
            @Override
            public byte[] mapRow(ResultSet resultSet, int i) throws SQLException {
            	//从数据表中查询出文件Blob
                Blob blob = resultSet.getBlob("file");
                //将Blob类型的数据转化为byte[]
                byte[] bytes = blobToBytes(blob);
                return bytes;
            }
        });
        //设置存储在本地的目录和名称
        File file = new File("C:\\temp","图片1.bmp");
        //写入到本地目录中
        writeFile(list.get(0),file);
    }

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现将jsp上传的文件保存数据库并且可以读出到界面上,需要以下步骤: 1. 在jsp页面添加上传文件的表单,例如: ```html <form action="upload.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 2. 在upload.jsp页面,获取上传的文件保存数据库,例如: ```java // 获取上传的文件 Part filePart = request.getPart("file"); InputStream fileContent = filePart.getInputStream(); // 将文件保存数据库 Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement pstmt = conn.prepareStatement("INSERT INTO files (name, content) VALUES (?, ?)"); pstmt.setString(1, filePart.getSubmittedFileName()); pstmt.setBlob(2, fileContent); pstmt.executeUpdate(); // 关闭连接 pstmt.close(); conn.close(); ``` 3. 在jsp页面读取数据库保存文件并显示到界面上,例如: ```java // 从数据库读取文件 Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM files"); // 显示文件列表 while (rs.next()) { String name = rs.getString("name"); Blob contentBlob = rs.getBlob("content"); InputStream contentStream = contentBlob.getBinaryStream(); // 显示文件名和内容 } // 关闭连接 rs.close(); stmt.close(); conn.close(); ``` 可以通过以上步骤实现将jsp上传的文件保存数据库并且可以读出到界面上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值