java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)
转自:https://blog.csdn.net/u014475796/article/details/49893261
在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情况。一般来说,我们可以通过插入文件相应的存储路径,而不是文件本身,来避免直接向数据库里插入的麻烦。但有些时候,直接向MySQL中插入文件,更加安全,而且更加容易管理。
首先,先要在数据库中建表。我在名为test的数据库下建立了一个叫pic的表。该表包括3列,id, caption和img。其中id是主键,caption是对图片的表述,img是图像文件本身。建表的SQL语句如下:
- DROP TABLE IF EXISTS `test`.`pic`;
- CREATE TABLE `test`.`pic` (
- `id` int(11) NOT NULL auto_increment,
- `caption` varchar(45) NOT NULL default '',
- `img` longblob NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
其次,在java中对文件(如图片,word文档等)的处理,其中包括把文件存储到数据库和从数据库中读取文件。(注:storeImg()和readImg()是可以处理任意文件类型的,不仅仅是图片)
</pre><pre name="code" class="sql"> 在数据库里存储文件以及从数据库读取文件的完整代码如下:
- <pre name="code" class="java">import java.io.*;
- import java.sql.*;
- public class StoreFile {
- private String dbDriver;
- private String dbURL;
- private String dbUser;
- private String dbPassword;
- private Connection con;
- private PreparedStatement ps;
- /**
- * 构造函数,初始化数据库的连接
- *
- */
- public StoreFile() {
- dbDriver = "com.mysql.jdbc.Driver";
- dbURL = "jdbc:mysql://localhost:3306/test";
- dbUser = "root";
- dbPassword = "justdoit";
- initDB();
- }
- public StoreFile(String strDriver, String strURL,
- String strUser, String strPwd) {
- dbDriver = strDriver;
- dbURL = strURL;
- dbUser = strUser;
- dbPassword = strPwd;
- initDB();
- }
- public void initDB() {
- try {
- // Load Driver
- Class.forName(dbDriver).newInstance();
- // Get connection
- con = DriverManager.getConnection(dbURL,
- dbUser, dbPassword);
- } catch(ClassNotFoundException e) {
- System.out.println(e.getMessage());
- } catch(SQLException ex) {
- // handle any errors
- System.out.println("SQLException: " + ex.getMessage());
- System.out.println("SQLState: " + ex.getSQLState());
- System.out.println("VendorError: " + ex.getErrorCode());
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * 将指定路径的文件(比如:图片,word文档等)存储到数据库
- * @param strFile 要存放到数据库的文件路径,如D:\\a.jpg
- */
- public void storeImg(String strFile) throws Exception {
- int id = 0;
- File file = new File(strFile);
- FileInputStream fis = new FileInputStream(file);
- try {
- ps = con.prepareStatement("insert "
- + "into PIC values (?,?,?)");
- ps.setInt(1, id);
- ps.setString(2, file.getName());
- ps.setBinaryStream(3, fis, (int) file.length());
- ps.executeUpdate();
- System.out.println("file insert success ");
- } catch (SQLException e) {
- System.out.println("SQLException: "
- + e.getMessage());
- System.out.println("SQLState: "
- + e.getSQLState());
- System.out.println("VendorError: "
- + e.getErrorCode());
- e.printStackTrace();
- } finally {
- ps.close();
- fis.close();
- con.close();
- }
- }
- /**
- * 将存储在数据库中的文件(比如:图片,word文档等)读取到指定路径
- * @param path 从数据库里读取出来的文件存放路径 如D:\\a.jpg
- * @param id 数据库里记录的id
- */
- public void readImg(String path, int id) throws Exception{
- initDB(); //建立与数据库的连接
- byte[] buffer = new byte[4096];
- FileOutputStream outputImage = null;
- InputStream is = null;
- try {
- ps = con.prepareStatement("select img from pic where id =?");
- ps.setInt(1, id);
- ResultSet rs = ps.executeQuery();
- rs.next();
- File file = new File(path);
- if (!file.exists()) {
- file.createNewFile();
- }
- outputImage = new FileOutputStream(file);
- Blob blob = rs.getBlob("img"); //img为数据库存放图片字段名称
- is = blob.getBinaryStream();
- int size = 0;
- while ((size = is.read(buffer)) != -1) {
- outputImage.write(buffer, 0, size);
- }
- System.out.println("file read success ");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- is.close();
- outputImage.close();
- ps.close();
- con.close();
- }
- }
- public static void main(String[] args) throws Exception {
- StoreFile sp = new StoreFile();
- String imgPath="C:\\Users\\Administrator\\Pictures\\img12.jpg";
- //String wordPath="d:\\测试文档.docx";
- sp.storeImg(imgPath);
- //sp.storeImg(wordPath);
- //sp.readImg("D://数据库.jpg", 1); //这里的1为要传入的参数:读取文件的id
- //sp.readImg("D://数据库.docx", 8);
- }
- }
java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)的更多相关文章
- ABBYY将JPEG文件转换成Word文档的方法
日常工作中处理JPEG格式的图像文件时,有时需要转换成Word文档进行编辑,市场上应用而生了很多转换工具,相信不少人听说过OCR(光学字符识别)软件,可以用来转换图像文件,而在OCR软件中, ABBY ...
- 如何使用ABBYY FineReader 12将JPEG文件转换成Word文档
日常工作中处理JPEG格式的图像文件时,有时需要转换成Word文档进行编辑,市场上应用而生了很多转换工具,相信不少人听说过OCR(光学字符识别)软件,可以用来转换图像文件,而在OCR软件中, ABBY ...
- C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)
这篇博客将要讨论的是关于: 如何从C#的source以及注释, 生成一份Word格式的关于各个类,函数以及成员变量的说明文档. 他的大背景如下...... 最近的一个项目使用C#, 分N个模块, 在项 ...
- springboot中使用freemarker生成word文档并打包成zip下载(简历)
一.设计出的简历模板图以及给的简历小图标切图 二.按照简历模板图新建简历word文件 :${字段名},同时将图片插入到word中,并将建好的word文件另存为xml文件: 三.直 ...
- 在项目中利用TX Text Control进行WORD文档的编辑显示处理
在很多文档管理的功能模块里面,我们往往需要对WORD稳定进行展示.编辑等处理,而如果使用微软word控件进行处理,需要安装WORD组件,而且接口使用也不见得简单易用,因此如果有第三方且不用安装Offi ...
- 将word文档A表格中的内容拷贝到word文档B表格中
Function IsFileExists(ByVal strFileName As String) As Boolean ) <> Empty Then IsFileExists = T ...
- 新建WORD文档打开会出现转换文件对话框3步解决办法
1.选择“纯文本”格式打开word文件. ------------------------------------------------------------------------------ ...
- pdf及word文档的读取 pyPDF2,docx
#!python3 #-*- coding:utf8 -*- #PyPDF2可能会打不开某些pdf文档,也不能提取图片,图表或者其他媒介从PDF文件中.但是它能提取文本从PDF中,转化为字符. imp ...
- 利用POI操作不同版本号word文档中的图片以及创建word文档
我们都知道要想利用java对office操作最经常使用的技术就应该是POI了,在这里本人就不多说到底POI是什么和怎么用了. 先说本人遇到的问题,不同于利用POI去向word文档以及excel文档去写 ...
随机推荐
- php-----utf8和gbk相互转换
utf8转换为gbk <?php header("Content-type:text/html;charset=UTF-8"); echo $str= '你好,这里是utf8 ...
- bzoj2330: [SCOI2011]糖果 差分约束系统
幼儿园里有N个小朋友,lxhgww老师现在想要给这些小朋友们分配糖果,要求每个小朋友都要分到糖果.但是小朋友们也有嫉妒心,总是会提出一些要求,比如小明不希望小红分到的糖果比他的多,于是在分配糖果的时候 ...
- html中用变量作为django字典的键值
若字典为dic={'name': Barbie, 'age': 20},则在html中dic.name为Barbie,dic.age为20. 但若字典为dic={'Barbie': 1, 'Roger ...
- java- Collection Map集合
package map; import java.util.Collection; import java.util.HashMap; import java.util.Map; import jav ...
- Shell排序算法和合并排序算法
Shell排序(希尔排序)算法Shell排序严格来说基于插入排序的思想,其又称为希尔排序或者缩小增量排序. Shell排序的流程:1.将由n个元素的数组分成n/2个数字序列,第1个数据和第n/2+1个 ...
- 中国的 Python 量化交易工具链有哪些
摘抄自知乎:https://www.zhihu.com/question/28557233 如题,提问的范围限于适合中国大陆金融市场使用的工具链,所以IbPy和Quotopian之类主要面向欧美市场的 ...
- c++ istringstream的用法
一.测试代码 istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流.这样就实现了字符串的空格切割. #include<iostream ...
- 复利计算5.0(改成Java版本)与 单元测试
//由于C语言版本不方便单元测试,所以改成了java版本,部分代码如下:import java.util.Scanner; public class FuLi{ public static void ...
- 【C++11】新特性 之 auto的使用
C++11中引入的auto主要有两种用途:自己主动类型判断和返回值占位.auto在C++98中的标识暂时变量的语义,因为使用极少且多余.在C++11中已被删除.前后两个标准的auto,全然是两个概 ...
- BinaryFormatter、SoapFormatter、XML3种序列化
序列化和反序列化我们可能经常会听到,其实通俗一点的解释,序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的时候把这个文件再转化成原来的对象使用.我想最主要的作用有:1.在进程下次 ...