Spring MVC 之文件上传(七)

时间:2021-06-20 20:44:36
SpringMVC同样使用了apache的文件上传组件。所以需要引入以下包:

apache-commons-fileupload.jar

apache-commons-io.jar

在springAnnotation-servlet.xml中配置

 <!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1"/><!-- -1代表不限制文件大小,单位是B -->
<property name="defaultEncoding" value="utf-8"/><!-- 设置字符集编码 -->
<property name="maxInMemorySize" value="1024"/><!-- 内存中最大内存空间,单位是B NO KB -->
</bean>

控制器:

 package com.cy.springannotation.controller;

 import java.io.File;

 import javax.servlet.http.HttpServletRequest;

 import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller
public class FileUploadController {
private Logger log = Logger.getLogger(this.getClass()); /**
* CommonsMultipartFile file
* @param file
* @return
*/
@RequestMapping(value="/upload.do",method=RequestMethod.POST)
public String upload(@RequestParam("fileName") CommonsMultipartFile file,HttpServletRequest req){
//获取原始文件名
String fileName = file.getOriginalFilename();
log.info(fileName);
String path = req.getSession().getServletContext().getRealPath("upload");
try {
file.getFileItem().write(new File(path + File.separator + fileName));
} catch (Exception e) { log.error(e);
}
return "success";
} }

上传文件页面:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>文件上传</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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="file" name="fileName"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form> </body>
</html>

上传文件就可以了!