标签:
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" p:maxUploadSize="5000000" p:uploadTempDir="upload/temp" />
@RequestMapping(value = "/upload")
public String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
HttpServletRequest request, ModelMap model) throws Exception {
if (!file.isEmpty()) {
// 保存文件-方式1 --测试过,可以用,必须先创建相应目录
// file.transferTo(new File("d:/"+file.getOriginalFilename()));
// 保存文件-方式2
String path = request.getSession().getServletContext()
.getRealPath("upload");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
//目录不存在,则创建目录
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
return "success";
} else {
return "fail";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>请上传用户头像</title>
</head>
<body>
<h1>请选择上传的头像文件</h1>
<form method="post" action="<c:url value="/test/upload.action"/>"
enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
【Spring学习笔记-MVC-13】Spring MVC之文件上传
标签:
原文地址:http://www.cnblogs.com/ssslinppp/p/4607043.html