springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)
參與該項目的文件上傳和下載。一旦struts2下完成,今天springmvc再來一遍。發現springmvc特別好包,基本上不具備的幾行代碼即可完成,下面的代碼貼:
FileUpAndDown.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>using commons Upload to upload file</title> </head> <script type="text/javascript"> function downFile(){var fileId = document.getElementById("fileId").value;location.href="fileDownload?fileId=" + fileId; } </script> <style> * {font-family: "宋體";font-size: 14px } </style> <body><p align="center">文件上傳下載</p><form id="form1" name="form1" method="post" action="fileUpload" enctype="multipart/form-data"><table border="0" align="center"><tr><td>上傳文件:</td><td><input name="file" type="file" size="20"></td></tr><tr><td></td><td><input type="submit" value="提交"> <input type="reset" name="reset" value="重置"></td></tr></table></form><div align="center"><input type="text" id="fileId"><input type="button" value="依據Id下載文件" οnclick="javascript:downFile()"></div> </body> </html>FileUpAndDownController.java @RequestMapping(value = "/fileUpload")public String upload(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request, ModelMap model) throws IOException {/*// 方式一:保存文件文件夾try {String path = request.getSession().getServletContext().getRealPath("/");// 文件保存文件夾,也可自定為絕對路徑String fileName = file.getOriginalFilename();// getOriginalFilename和getName是不一樣的哦System.out.println(path);File targetFile = new File(path, fileName);if (!targetFile.exists()) {targetFile.mkdirs();}file.transferTo(targetFile);model.addAttribute("upload.message", request.getContextPath() + "/upload/" + fileName);} catch (Exception e) {e.printStackTrace();}*/// 方式二:保存入庫Map<String, Object> insertMap = new HashMap<String, Object>();insertMap.put("byt", file.getBytes());insertMap.put("fileName", file.getOriginalFilename());int flag = fileUpAndDownMapper.saveFileInfo(insertMap);if(flag > 0)model.addAttribute("upload.message", "success");elsemodel.addAttribute("upload.message", "failure");return "/core/param/businessparam/uploadResult";}
FileUpAndDownMapper.xml(相應的數據庫為db2,保存blob類型) <?xml version="1.0" encoding="UTF-8"?
> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xx.persistence.FileUpAndDownMapper"> <resultMap id="fileBean" type="com.xx.web.FileUpAndDown"> <id column="ID" property="id" jdbcType="INTEGER" /> <result column="FILENAME" property="fileName" jdbcType="VARCHAR" /> <result column="TESTA" property="testa" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" /> <result column="FILESTREAM" property="fileStream" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" /> </resultMap> <insert id="saveFileInfo" parameterType="java.util.HashMap"> INSERT INTO BLOBTEST(FILENAME, FILESTREAM) VALUES(#{fileName}, #{byt, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}) </insert> <select id="getFileByPk" resultMap="fileBean" parameterType="int"> SELECT * FROM BLOBTEST WHERE ID=${value} </select> </mapper>
uploadResult.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>uploadResult</title><meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body><a href="fileManagePage">上傳文件</a> ${requestScope['upload.message'] } </body> </html>
以上為springmvc下上傳文件的Demo,當中非常關鍵的一步是。spring的配置文件里要增加文件上傳的支持: <!-- 支持上傳文件 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
文件的保存做了兩種方式,一種是直接存server的文件文件夾;還有一種是把文件流存入數據庫blob字段內(項目的特須要求)
以下是文件下載的代碼:
@ResponseBody@RequestMapping(value = "/fileDownload")public void fileDownload(HttpServletRequest request,HttpServletResponse response) throws IOException {String fileId = request.getParameter("fileId");FileUpAndDown file = fileUpAndDownMapper.getFileByPk(Integer.parseInt(fileId));byte[] fileStream = file.getFileStream();String fileName = file.getFileName();// 以流的形式下載文件response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"), "ISO8859-1" ) + "\"");OutputStream toClient = new BufferedOutputStream(response.getOutputStream());toClient.write(fileStream);toClient.flush();toClient.close();}springmvc下文件上傳下載非常easy明對?不喜歡servlet在這么多的代碼。
轉載于:https://www.cnblogs.com/mengfanrong/p/4606125.html
總結
以上是生活随笔為你收集整理的springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ 2440: [中山市选2011
- 下一篇: CentOS 6.6 Oracle 安装