转自:https://blog.csdn.net/u014475796/article/details/49893261

在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情况。一般来说,我们可以通过插入文件相应的存储路径,而不是文件本身,来避免直接向数据库里插入的麻烦。但有些时候,直接向MySQL中插入文件,更加安全,而且更加容易管理。
  首先,先要在数据库中建表。我在名为test的数据库下建立了一个叫pic的表。该表包括3列,id, caption和img。其中id是主键,caption是对图片的表述,img是图像文件本身。建表的SQL语句如下:
  1.  
    DROP TABLE IF EXISTS `test`.`pic`;
  2.  
    CREATE TABLE `test`.`pic` (
  3.  
    `id` int(11) NOT NULL auto_increment,
  4.  
    `caption` varchar(45) NOT NULL default '',
  5.  
    `img` longblob NOT NULL,
  6.  
    PRIMARY KEY (`id`)
  7.  
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  其次,在java中对文件(如图片,word文档等)的处理,其中包括把文件存储到数据库和从数据库中读取文件。(注:storeImg()和readImg()是可以处理任意文件类型的,不仅仅是图片)
</pre><pre name="code" class="sql">  在数据库里存储文件以及从数据库读取文件的完整代码如下:
  1.  
    <pre name="code" class="java">import java.io.*;
  2.  
    import java.sql.*;
  3.  
    public class StoreFile {
  4.  
     
  5.  
    private String dbDriver;
  6.  
    private String dbURL;
  7.  
    private String dbUser;
  8.  
    private String dbPassword;
  9.  
    private Connection con;
  10.  
    private PreparedStatement ps;
  11.  
    /**
  12.  
    * 构造函数,初始化数据库的连接
  13.  
    *
  14.  
    */
  15.  
    public StoreFile() {
  16.  
    dbDriver = "com.mysql.jdbc.Driver";
  17.  
    dbURL = "jdbc:mysql://localhost:3306/test";
  18.  
    dbUser = "root";
  19.  
    dbPassword = "justdoit";
  20.  
    initDB();
  21.  
    }
  22.  
    public StoreFile(String strDriver, String strURL,
  23.  
    String strUser, String strPwd) {
  24.  
    dbDriver = strDriver;
  25.  
    dbURL = strURL;
  26.  
    dbUser = strUser;
  27.  
    dbPassword = strPwd;
  28.  
    initDB();
  29.  
    }
  30.  
     
  31.  
    public void initDB() {
  32.  
    try {
  33.  
    // Load Driver
  34.  
    Class.forName(dbDriver).newInstance();
  35.  
    // Get connection
  36.  
    con = DriverManager.getConnection(dbURL,
  37.  
    dbUser, dbPassword);
  38.  
    } catch(ClassNotFoundException e) {
  39.  
    System.out.println(e.getMessage());
  40.  
    } catch(SQLException ex) {
  41.  
    // handle any errors
  42.  
    System.out.println("SQLException: " + ex.getMessage());
  43.  
    System.out.println("SQLState: " + ex.getSQLState());
  44.  
    System.out.println("VendorError: " + ex.getErrorCode());
  45.  
     
  46.  
    } catch (Exception e) {
  47.  
    System.out.println(e.getMessage());
  48.  
    }
  49.  
    }
  50.  
    /**
  51.  
    * 将指定路径的文件(比如:图片,word文档等)存储到数据库
  52.  
    * @param strFile 要存放到数据库的文件路径,如D:\\a.jpg
  53.  
    */
  54.  
    public void storeImg(String strFile) throws Exception {
  55.  
    int id = 0;
  56.  
    File file = new File(strFile);
  57.  
    FileInputStream fis = new FileInputStream(file);
  58.  
    try {
  59.  
    ps = con.prepareStatement("insert "
  60.  
    + "into PIC values (?,?,?)");
  61.  
    ps.setInt(1, id);
  62.  
    ps.setString(2, file.getName());
  63.  
    ps.setBinaryStream(3, fis, (int) file.length());
  64.  
    ps.executeUpdate();
  65.  
    System.out.println("file insert success ");
  66.  
    } catch (SQLException e) {
  67.  
    System.out.println("SQLException: "
  68.  
    + e.getMessage());
  69.  
    System.out.println("SQLState: "
  70.  
    + e.getSQLState());
  71.  
    System.out.println("VendorError: "
  72.  
    + e.getErrorCode());
  73.  
    e.printStackTrace();
  74.  
    } finally {
  75.  
    ps.close();
  76.  
    fis.close();
  77.  
    con.close();
  78.  
    }
  79.  
    }
  80.  
    /**
  81.  
    * 将存储在数据库中的文件(比如:图片,word文档等)读取到指定路径
  82.  
    * @param path 从数据库里读取出来的文件存放路径 如D:\\a.jpg
  83.  
    * @param id 数据库里记录的id
  84.  
    */
  85.  
    public void readImg(String path, int id) throws Exception{
  86.  
    initDB(); //建立与数据库的连接
  87.  
    byte[] buffer = new byte[4096];
  88.  
    FileOutputStream outputImage = null;
  89.  
    InputStream is = null;
  90.  
    try {
  91.  
    ps = con.prepareStatement("select img from pic where id =?");
  92.  
    ps.setInt(1, id);
  93.  
    ResultSet rs = ps.executeQuery();
  94.  
    rs.next();
  95.  
    File file = new File(path);
  96.  
    if (!file.exists()) {
  97.  
    file.createNewFile();
  98.  
    }
  99.  
    outputImage = new FileOutputStream(file);
  100.  
    Blob blob = rs.getBlob("img"); //img为数据库存放图片字段名称
  101.  
    is = blob.getBinaryStream();
  102.  
    int size = 0;
  103.  
    while ((size = is.read(buffer)) != -1) {
  104.  
    outputImage.write(buffer, 0, size);
  105.  
    }
  106.  
    System.out.println("file read success ");
  107.  
    } catch (Exception e) {
  108.  
    e.printStackTrace();
  109.  
    } finally {
  110.  
    is.close();
  111.  
    outputImage.close();
  112.  
    ps.close();
  113.  
    con.close();
  114.  
    }
  115.  
    }
  116.  
     
  117.  
    public static void main(String[] args) throws Exception {
  118.  
    StoreFile sp = new StoreFile();
  119.  
    String imgPath="C:\\Users\\Administrator\\Pictures\\img12.jpg";
  120.  
    //String wordPath="d:\\测试文档.docx";
  121.  
    sp.storeImg(imgPath);
  122.  
    //sp.storeImg(wordPath);
  123.  
    //sp.readImg("D://数据库.jpg", 1); //这里的1为要传入的参数:读取文件的id
  124.  
    //sp.readImg("D://数据库.docx", 8);
  125.  
    }
  126.  
    }

java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)的更多相关文章

  1. ABBYY将JPEG文件转换成Word文档的方法

    日常工作中处理JPEG格式的图像文件时,有时需要转换成Word文档进行编辑,市场上应用而生了很多转换工具,相信不少人听说过OCR(光学字符识别)软件,可以用来转换图像文件,而在OCR软件中, ABBY ...

  2. 如何使用ABBYY FineReader 12将JPEG文件转换成Word文档

    日常工作中处理JPEG格式的图像文件时,有时需要转换成Word文档进行编辑,市场上应用而生了很多转换工具,相信不少人听说过OCR(光学字符识别)软件,可以用来转换图像文件,而在OCR软件中, ABBY ...

  3. C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)

    这篇博客将要讨论的是关于: 如何从C#的source以及注释, 生成一份Word格式的关于各个类,函数以及成员变量的说明文档. 他的大背景如下...... 最近的一个项目使用C#, 分N个模块, 在项 ...

  4. springboot中使用freemarker生成word文档并打包成zip下载(简历)

    一.设计出的简历模板图以及给的简历小图标切图         二.按照简历模板图新建简历word文件 :${字段名},同时将图片插入到word中,并将建好的word文件另存为xml文件:    三.直 ...

  5. 在项目中利用TX Text Control进行WORD文档的编辑显示处理

    在很多文档管理的功能模块里面,我们往往需要对WORD稳定进行展示.编辑等处理,而如果使用微软word控件进行处理,需要安装WORD组件,而且接口使用也不见得简单易用,因此如果有第三方且不用安装Offi ...

  6. 将word文档A表格中的内容拷贝到word文档B表格中

    Function IsFileExists(ByVal strFileName As String) As Boolean ) <> Empty Then IsFileExists = T ...

  7. 新建WORD文档打开会出现转换文件对话框3步解决办法

    1.选择“纯文本”格式打开word文件.  ------------------------------------------------------------------------------ ...

  8. pdf及word文档的读取 pyPDF2,docx

    #!python3 #-*- coding:utf8 -*- #PyPDF2可能会打不开某些pdf文档,也不能提取图片,图表或者其他媒介从PDF文件中.但是它能提取文本从PDF中,转化为字符. imp ...

  9. 利用POI操作不同版本号word文档中的图片以及创建word文档

    我们都知道要想利用java对office操作最经常使用的技术就应该是POI了,在这里本人就不多说到底POI是什么和怎么用了. 先说本人遇到的问题,不同于利用POI去向word文档以及excel文档去写 ...

随机推荐

  1. Luogu P4062 [CTSC2018]混合果汁 (主席树)

    二分$d$, 转为判断判断是否能取到$Lj$升, 再可持久化一下就好了 #include <iostream> #include <algorithm> #include &l ...

  2. 51nod-1420-贪心

    1420 数袋鼠好有趣  题目来源: CodeForces 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题  收藏  关注 有n只袋鼠.每只袋鼠的大小用一个整数表示 ...

  3. linux hosts.equiv设置解析

    hosts.equiv文件的用途与格式 一. hosts.equiv 文件的用途 /etc/hosts.equiv 和 $HOME/.rhosts 定义了哪些计算机和用户可以不用提供口令就在本地计算机 ...

  4. https ddos攻击——由于有了认证和加解密 后果更严重 看绿盟的产品目前对于https的ddos cc攻击需要基于内容做检测

    如果web服务器支持HTTPS,那么进行HTTPS洪水攻击是更为有效的一种攻击方式,一方面,在进行HTTPS通信时,web服务器需要消耗更多的资源用来进行认证和加解密,另一方面,一部分的防护设备无法对 ...

  5. UVA 11624 Fire! bfs 难度:0

    http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&p ...

  6. Centos7 防火墙常用命令 开启 关闭防火墙

    如果你的系统上没有安装使用命令安装 #yum install firewalld  //安装firewalld 防火墙 开启服务 # systemctl start firewalld.service ...

  7. 简单使用dom4j

    package com.dom4j; import java.io.FileWriter; import java.io.IOException; import java.io.Unsupported ...

  8. 关于React setState的实现原理(一)

    前言 首先在学习react的时候就对setSate的实现有比较浓厚的兴趣,那么对于下边的代码,可以快速回答吗? class Root extends React.Component { constru ...

  9. 内存泄漏 之 MAT工具的使用

    1 内存泄漏的排查方法 Dalvik Debug Monitor Server (DDMS) 是 ADT插件的一部分,其中有两项功能可用于内存检查 : ·    heap 查看堆的分配情况 ·     ...

  10. BZOJ3195: [Jxoi2012]奇怪的道路【状压DP】

    Description 小宇从历史书上了解到一个古老的文明.这个文明在各个方面高度发达,交通方面也不例外.考古学家已经知道,这个文明在全盛时期有n座城市,编号为1..n.m条道路连接在这些城市之间,每 ...