最近在做一个文件上传的功能,走了不少弯路,话不多说,直接上代码:
导入各种jar包,首先是applicationContext.xml配置文件中:
<!-- 配置文件解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
写两个前端页面:upLoad.jsp
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"/><br>
头像:<input type="file" name="mf"/><br>
姓名:<input type="submit" value="上传"/>
</form>
</body>
show.jsp
<body>
<h1>head image</h1>
<img alt="" src="${image }" style="width: 400px;height: 500px">
</body>
然后进入正题,写一个上传的战士页面的controller
@RequestMapping("/toUpload.do") //SpringMVC的映射标注
public String toUpload(){
return "upload";
}
然后
@Controller
public class FileUploadController { // MultipartFile 用于接受文件对象
@RequestMapping("/upload.do") // MultipartFile用于接受用户名和数据,否则文件上传时候也上encytype后悔接收不到数据
public String upload(String username, MultipartFile mf, HttpServletRequest req) { System.out.println(username + "||" + mf.getOriginalFilename() + "||" + mf.getSize());
// 把文件写入响应路径下
String realpath = req.getServletContext().getRealPath("images");// 获取到当前文件夹的真是路径
String orName = mf.getOriginalFilename();// 获取文件的原始名字
String fileName = System.currentTimeMillis() + orName.substring(orName.lastIndexOf("."));// 修改上传文件的名字,时间加后缀
String filePath = realpath + "/" + fileName;
System.out.println(filePath);
File file = new File(filePath);// 创建一个文件对象
try {
mf.transferTo(file);// 将文件写入到路径中
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
req.setAttribute("image", "images/" + fileName);
return "show";
}
}
OK!,大功告成!