Spring3.0 入门进阶(5):文件的上传与下载

Spring web模块支持文件的上传与下载,下面两个章节分别介绍对应的内容

文件的上传

依赖的JAR

主要用到commons-fileupload-1.3.jar以及commons-io-2.4.jar.

如果使用Maven,可添加如下配置

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3</version>
</dependency>

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

修改页面

首先要使对应的form支持文件的提交,增加enctype属性

<fm:form method="POST" modelAttribute="NewSpitter" enctype="multipart/form-data">

再添加如下代码块到form中

<tr>
	<td><label for="pic">Pic:</label></td>
	<td><input name="pic" type="file"></td>
</tr>

修改控制器

添加@RequestParam(value = "pic", required = false) MultipartFile 到控制器的对应方法的参数中,并且对上传文件进行处理

/**
	 * 该方法没有指定处理的路径,表示可以处理的路径是
	 * /spitter,且method是POST,@Valid表示在传入Spitter对象作为方法的参数之前,
	 * 会进行值的校验,并将结果存在BindingResult中
	 * 
	 * @param spitter
	 *            , 在newspitter.jsp中编辑的对象
	 * @param result
	 *            , 通过redirect 的方式返回路径
	 * @param uploadFile
	 *            , 支持文件上传.RequestRaram 中的"pic"的值应该和页面中上传组件的名字相同
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String addSpitter(
			@ModelAttribute("NewSpitter") @Valid Spitter spitter,
			BindingResult result,
			@RequestParam(value = "pic", required = false) MultipartFile uploadFile)
			throws IOException {
		if (result.hasFieldErrors()) {
			return "spitter/edit";
		}
                //文件上传的处理
               if (uploadFile != null) {
			if (uploadFile.getContentType().equalsIgnoreCase("image/jpeg")) {
				File file = new File("./resouces/pic/"
						+ System.currentTimeMillis() + ".jpeg");
				FileUtils.writeByteArrayToFile(file, uploadFile.getBytes());
			}
		}
		spitterService.addSpitter(spitter);
		return "redirect:/spitter/" + spitter.getUserName();
	}

修改配置文件

<!-- 上传拦截,如最大上传值及最小上传值 -->  
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- one of the properties available; the maximum file size in bytes -->  
        <property name="maxUploadSize" value="100000" />  
    </bean> 


文件的下载

文件的下载相对比较简单,只需要修改对应的控制器便可.为了演示,在D:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.21\bin\resouces\pic\ 目录下放了一个1390110889206.jpeg文件,下面的改动将演示如何下载该文件

控制器的代码

       /**下载指定的文件
       *访问路径:http://localhost:8080/SpringInActionWebSample/spitter/downloadfile
         * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("downloadfile")
	public ModelAndView downloadTest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String storeName = "1390110889206.jpeg";
		String realName = "test.jpeg";
		String contentType = "application/octet-stream";
		download(request, response, storeName, contentType, realName);
		return null;
	}

	/**指定下载一个图片,如有需要可以对此方法进行扩展
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public void download(HttpServletRequest request,
			HttpServletResponse response, String storeName, String contentType,
			String realName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String rootDir="./resouces/pic/";
		String downLoadPath = rootDir + storeName;
		long fileLength = new File(downLoadPath).length();
		response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}



你可能感兴趣的:(文件上传,文件下载,Spring3)