SpringMVC处理MySQL BLOB字段的下载
任务:
uos.docfile的content字段是longblob类型,通过Web点击链接能下载到存储在这个字段里的文件。Web点击链接类似如下形式:
http://localhost:8080/dld/downloadDocument.html?id=81&&filename=jfreechart-1.0.19.zip
1.控制器代码:
@RequestMapping("/downloadDocument") public ModelAndView downloadDocument(HttpServletRequest request,HttpServletResponse response){ try { // 取参数 String id=request.getParameter("id"); String filename=request.getParameter("filename"); // 设置Resposne response.reset(); response.setHeader("Content-disposition", "attachment; filename="+filename); response.setContentType("text/x-plain"); // 获得输出流 ServletOutputStream out = response.getOutputStream(); // 从数据库拷贝输出流 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096); service.copyDocumentOutputStream(id, byteOutputStream); logger.info(" call PosService.copyDocumentOutputStream successfully."); // 转化 byte[] bt = null; bt = byteOutputStream.toByteArray(); // 向客户端写输出 out.write(bt); out.flush(); out.close(); return null; } catch (Exception e) { e.printStackTrace(); logger.error(e); request.setAttribute("error", e.getClass()); request.setAttribute("reason", e.getMessage()); StackTraceElement[] arr=e.getStackTrace(); request.setAttribute("stackTraceElements", arr); return new ModelAndView("pages/error/index.jsp"); } }
2.Service中代码,同样这里也只是中转
public void copyDocumentOutputStream(final String id, final OutputStream os) throws Exception{ getPosDao().copyDocumentOutputStream(id, os); }
3.DAO中代码,这里是实质代码
public void copyDocumentOutputStream(final String id, final OutputStream os) throws Exception{ final LobHandler lobHandler=new DefaultLobHandler(); this.getJdbcTemplate().query("select content from uos.docfile where id=?",new String[] {id},new AbstractLobStreamingResultSetExtractor(){ protected void streamData(ResultSet rs) throws SQLException,IOException,DataAccessException{ FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs,1),os); } }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)