博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java blob 文件上传下载
阅读量:7091 次
发布时间:2019-06-28

本文共 1932 字,大约阅读时间需要 6 分钟。

1、文件上传

pojo中为byte[] 类型,数据库中对应为blob类型。

主要代码:

FileInputStream fis = null;fis = new FileInputStream(new File(filePath));byte[] inputByte = input2byte(fis);fileBean.setContent(inputByte);/*** 将 流 转换为byte* @param inStream* @return* @throws IOException*/public static final byte[] input2byte(InputStream inStream) throws IOException {   ByteArrayOutputStream swapStream = null;  try {    swapStream = new ByteArrayOutputStream();    byte[] buff = new byte[1024];     int rc = 0;     while ((rc = inStream.read(buff, 0, 1024)) > 0) {       swapStream.write(buff, 0, rc);     }     return swapStream.toByteArray();  } catch (Exception e) {    logger.info(e.getStackTrace());  } finally {    if (swapStream != null) {    safeClose(swapStream);    }  }  return null;} 

2、文件下载

@Overridepublic void downFileByBlob(HttpServletRequest request, HttpServletResponse response, String fileId) throws IOException {  AtFileupload bean = hibernateDao.getObject(AtFileupload.class, fileId);  if (bean.getContent() != null) {    String filename= bean.getFileName();//获取日志中存储的文件名称    String userAgent = request.getHeader("user-agent").toLowerCase();     if (userAgent.contains("msie") || userAgent.contains("like gecko")) {     // IE       filename = URLEncoder.encode(filename, "UTF-8");     } else {     // 非IE       filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");     }     try {      byte[] fileStream = bean.getContent();      // 以流的形式下载文件        response.setContentType("application/x-msdownload");        response.setCharacterEncoding("UTF-8");        response.setHeader("Content-Disposition", "attachment; filename=" + filename);        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());        toClient.write(fileStream);        toClient.flush();        toClient.close();      } catch (Exception e) {        logger.info(e.getStackTrace());      }   }}

转载于:https://www.cnblogs.com/eyesmoon/p/7644382.html

你可能感兴趣的文章
mysql数据库的简单语句的介绍(1)
查看>>
HDU 2829 Lawrence (斜率DP)
查看>>
visual studio 2012 update3
查看>>
特征值和特征向量的几何意义、计算及其性质
查看>>
Spring framework3.2整合hibernate4.1报错:No Session found for current thread
查看>>
zqgame《每日一言》
查看>>
前端与后端分离的架构实例(一)
查看>>
LoadRunner性能分析指标解释
查看>>
OC语言类的本质和分类
查看>>
如何实现phpcms v9_4X版本tag的伪静态?
查看>>
w3c标准的selection对象介绍
查看>>
Python-类属性与对象属性之间的关系
查看>>
JavaScript 函数参数传递到底是值传递还是引用传递
查看>>
LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium...
查看>>
解决 No Entity Framework provider found for the ADO.NET provider
查看>>
转 用 Chrome 运行Android应用
查看>>
编程心得--不积跬步无以至千里
查看>>
thinkphp学习笔记8—命名空间
查看>>
在项目中几个需要学习的知识
查看>>
验证码安全问题汇总
查看>>