数据库:mysql + mybatis

文件:本项目保存的是excel文件,其他文件应该也是适用的

最近由于项目原因,需将文件保存到数据库中,最先开始设计新增一个类型为blob的字段,结果保存没有问题,但下载的时候如果该excel文件里包含特殊公式,或者版本不兼容时,会丢失样式和内容,最终解决方式:将bolb类型改为mediumtext(或则text),text最大支持64kb的文件,mediumtext最大支持16M的文件,可视情况进行设置

例如:alter table ab_report_history add column fileContent mediumtext COMMENT '文件内容';

重点:保存时将文件转换为String后,base64编码,下载时将内容取出来,base64解码

示例:

java代码:

保存时:

AbReportHistory record = new AbReportHistory();

record.setFileContent(FileUtil.encodeBase64File(myfile)); //注意此方法

下载时:

new BASE64Decoder().decodeBuffer(编码后的string); //通过此方法解码

java字段类型:

private String fileContent;

mybatis

--------------------------------以上是将文件保存到数据库的关键内容--------------------------------------------------------

以下提供相关工具类:

package *.*.*.*;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

/**

* 文件操作工具类

* @author sunddylee

* @date 2016年12月20日

*

*/

public class FileUtil {

/**

* NIO way

* 读取excel文件

* @param filePath

* @param fileName

* @throws Exception

*/

public static byte[] readExcelFiletoByteArray(String filePath) throws Exception {

File f = new File(filePath);

if (!f.exists()) {

throw new FileNotFoundException(filePath);

}

FileChannel channel = null;

FileInputStream fs = null;

try {

fs = new FileInputStream(f);

channel = fs.getChannel();

ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());

while ((channel.read(byteBuffer)) > 0) {

// do nothing

// System.out.println("reading");

}

return byteBuffer.array();

} catch (IOException e) {

e.printStackTrace();

throw e;

} finally {

try {

channel.close();

} catch (IOException e) {

e.printStackTrace();

}

try {

fs.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 下载excel文件

* @param response

* @param filePath

* @param fileName:带有后缀名的文件名 例如 a.xls

* @throws Exception

*/

public static void downloadExcelFile(HttpServletResponse response, String filePath, String fileName) throws Exception {

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

try {

// 设置response参数,可以打开下载页面

response.reset();

response.setContentType("application/vnd.ms-excel;charset=utf-8");

response.setHeader("Content-Disposition", "attachment;filename="

+ new String((fileName).getBytes(), "iso-8859-1"));

ServletOutputStream out = response.getOutputStream();

bis = new BufferedInputStream(new FileInputStream(filePath));

bos = new BufferedOutputStream(out);

byte[] buff = new byte[2048];

int bytesRead;

// Simple read/write loop.

while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {

bos.write(buff, 0, bytesRead);

}

} catch (IOException e) {

throw e;

} finally {

if (bis != null)

bis.close();

if (bos != null)

bos.close();

}

}

public static void downloadExcelFile(HttpServletResponse response, String fileName, byte[] fileContent) throws Exception {

BufferedOutputStream bos = null;

try {

// 设置response参数,可以打开下载页面

response.reset();

response.setContentType("application/vnd.ms-excel;charset=utf-8");

response.setHeader("Content-Disposition", "attachment;filename="

+ new String((fileName).getBytes(), "iso-8859-1"));

ServletOutputStream out = response.getOutputStream();

bos = new BufferedOutputStream(out);

if(null != fileContent){

bos.write(fileContent);

}

} catch (IOException e) {

throw e;

} finally {

if (bos != null)

bos.close();

}

}

/**

* 将文件转成base64 字符串

* @param path文件路径

* @return *

* @throws Exception

*/

public static String encodeBase64File(String path) throws Exception {

File file = new File(path);

FileInputStream inputFile = new FileInputStream(file);

byte[] buffer = new byte[(int) file.length()];

inputFile.read(buffer);

inputFile.close();

return new BASE64Encoder().encode(buffer);

}

public static String encodeBase64File(MultipartFile file) throws Exception {

return new BASE64Encoder().encode(file.getBytes());

}

public static byte[] decoderBase64File(String base64Code) throws Exception {

return new BASE64Decoder().decodeBuffer(base64Code);

}

/**

* 将base64字符解码保存文件

* @param base64Code

* @param targetPath

* @throws Exception

*/

public static void decoderBase64File(String base64Code, String targetPath)

throws Exception {

byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);

FileOutputStream out = new FileOutputStream(targetPath);

out.write(buffer);

out.close();

}

/**

* 将base64字符保存文本文件

* @param base64Code

* @param targetPath

* @throws Exception

*/

public static void toFile(String base64Code, String targetPath)

throws Exception {

byte[] buffer = base64Code.getBytes();

FileOutputStream out = new FileOutputStream(targetPath);

out.write(buffer);

out.close();

}

public static void main(String[] args) {

try {

String base64Code = encodeBase64File("E:\\test\\test1.xls");

System.out.println(base64Code);

decoderBase64File(base64Code, "E:\\test\\test.xls");

// toFile(base64Code, "D:\\three.txt");

} catch (Exception e) {

e.printStackTrace();

}

}

}

mysql 字段存文件_使用数据库(mysql)字段保存文件相关推荐

  1. mysql 字段长度建议_设计数据库时字段类型和长度建议

    对于任何字段长度都不应该过于小气,否则未知的变化会造成前后台都要修改 1.对于开关型字段建议number(1,0) 而不是varchar2(1),避免用户错误保存Y/N,而不是1/0,这样可能会引入大 ...

  2. mysql数据对比同步_跨数据库mysql语句同步数据和对比运算

    首先,A数据库[需要同步的数据库]A_product数据表[产品基本信息]product_id产品唯一IDprice产品价格A_product_option_value数据表[产品选项]product ...

  3. mysql数据库存歌_如何在mysql中存储音乐和图片文件

    标签: 如何在mysql中存储音乐和图片文件? 果你想把二进制的数据,比如说图片文件和HTML文件,直接保存在你的MySQL数据库,那么这篇文章就是为你而写的! 我将告诉你怎样通过HTML表单来储存这 ...

  4. mysql指令按顺序排列_《深入浅出MySQL》读书笔记(一)sql基础,常用的操作语句。...

    之前对于数据库一直都是用过的程序,没有系统学过,在面试时吃过不少亏,说不出个所以然,我还是好好康康比较靠谱,秋招都快过了,我好慌啊淦. 第一章.MySQL的安装与配置. 启动服务:打开到mysql对应 ...

  5. mysql 联查字段名重复_查询数据库多个字段名时的结果有重复的解决办法_MySQL

    bitsCN.com 查询数据库多个字段名时的结果有重复的解决办法 查询数据库的结果有重复,怎么办? 在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供有distinct这个关 ...

  6. mysql查看数据库的日志文件_怎么查看mysql数据库的日志文件

    2017-10-16 回答 一.错误日志 错误日志在mysql数据库中很重要,它记录着mysqld启动和停止,以及服务器在运行过程中发生的任何错误的相关信息. 1.配置信息 --log-error=[ ...

  7. 删除安装的mysql数据库文件_安装/删除MySQL数据库

    安装包我会放在本文的底部,如果需要自取 MySQL的数据存储目录为data,data目录通常在C:\Documents and Settings\All Users\Application Data\ ...

  8. 如何设置mysql的运行目录_如何修改mysql数据库文件的路径 | 学步园

    在网上找了好多,没有确定哪个是最终的答案,由于网站在运行中,实在不敢轻易动手,怎么奈我是个菜鸟呢!先把找到的东西简单记录一下,回头再说! 还有一个: 首先在数据库里看一下数据库里当前数据文件的存放路径 ...

  9. mysql中的gcache.page文件_高可用MySQL数据库之PXC集群

    前言 在上一篇文章介绍了时下流行的几种数据库产品后(公众号发送"NewSQL"查看),有不少小伙伴表示对自动集群的数据库感兴趣,特别是CockroachDB数据库,但是现有的业务使 ...

最新文章

  1. 算法 | 数据结构与算法(代码版)
  2. Mysql 主从数据库同步详解
  3. linux11g导入10g 怎么改版本,Oracle 11g导入到10g引起的错误
  4. (17)Vivado IP综合选项Global和Out-Of-Context区别(FPGA不积跬步101)
  5. python3导入模块原理_python模块导入原理
  6. centos7:安装配置 virtualbox 增强功能 VBoxGuestAdditions,并实现物理机脚本控制虚拟机
  7. 手把手教你创建 Alexa Smart Home Skill (二)
  8. matlab表示双曲函数,MATLAB2009_1_5三角函数和双曲函数
  9. 第三方支付和聚合支付
  10. 移动互联网创业组织可持续发展模型
  11. 5.21 将表格恢复到排序前的状态 [原创Excel教程]
  12. 顺丰云服务器,基于华为云云原生解决方案,顺丰“快递+”这一项业务效率提升了48倍...
  13. easyexcel使用问题:使用时导出的excel文件损坏,打开不了,后台没异常错误
  14. 透明与不透明物体共存
  15. 计算机屏幕位置高低,电脑显示器的最佳位置
  16. Navigation Controller 的常用操作
  17. 移动端布局介绍——css像素/物理像素/设备像素比
  18. Java实现迪杰斯特拉算法
  19. 系统安装报错:dracut-initqueue : Warning: dracut-initqueue timeout - starting timeout scripts
  20. 没有光驱,你能装系统吗?

热门文章

  1. 终于!这本Python书彻底玩大了!
  2. 程序员该如何转型 5G 开发?
  3. Python 最抢手、Java 最流行、Go 最有前途,7000 位程序员揭秘 2019 软件开发现状...
  4. 程序员如何用编程套路追到女朋友的?
  5. 熬夜写代码,不如换女装入 GitHub 获上千 Star?
  6. Visual Studio Code 1.30 发布,你升级了没?
  7. 什么叫做支路_你知道什么叫电路图的了吧...
  8. oracledatabase11gr2怎么打开_oracle database 11gR2 + forms and reports 11g安装教程
  9. java冒泡怎么写_java 冒泡 又一种写法
  10. python shutil模块用法实例分析_python之shutil模块使用方法(三分钟了解)