SpringMVC配置文件中需要添加:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" />
注意id必须为multipartResolver
控制器中:
@Controller
@RequestMapping("file")
public class UploadFileController {
@RequestMapping("/uploadFile.action")
public String uploadFile(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 页面控件的文件流
MultipartFile multipartFile = multipartRequest.getFile("file");
// 创建文件保存位置
ServletContext context = request.getServletContext();
String savePath = context.getRealPath("/upload/");
java.io.File folder = new java.io.File(savePath);
if (!folder.exists()) {
folder.mkdirs();
}
System.out.println("文件保存路径:" + savePath);
// 保存文件的名称
String rndFilename = (new SimpleDateFormat("yyyyMMddHHmmss"))
.format(new Date());
// 获取文件的真实名称
String fileName = multipartFile.getOriginalFilename();
// 文件的后缀
String ext = fileName.substring(fileName.lastIndexOf("."));
long size = multipartFile.getSize()/1024;//kb
java.io.File file = new java.io.File(savePath+"/"+rndFilename+ext);
try {
multipartFile.transferTo(file);
} catch (Exception e) {
e.printStackTrace();
}
return "index";
}
}
前台jsp:
<script type="text/javascript">
function check(){
var file = document.getElementById("file").value;
if(file == ""){
alert("请上传文件!");
return false;
}
return true;
}
</script>
<body>
<form action="file/uploadFile.action" method="post" enctype="multipart/form-data" οnsubmit="return check()">
<input type="file" name="file" id="file" />
<input type="submit" value="上传">
<input type="button" value="返回" >
</form>
</body>