1. 程式人生 > >springmvc和servlet下的檔案上傳和下載(存檔案目錄和存資料庫Blob兩種方式)

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下載檔案" onclick="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");
		else
			model.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"/>

檔案的儲存做了兩種方式,一種是直接存伺服器的檔案目錄;另一種是把檔案流存入資料庫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下檔案上傳下載很簡單明瞭吧?不必像servlet下那麼多的程式碼。