1.jsp代码
<form id="jvForm" action="upload.do" method="post" enctype="multipart/form-data">
<table cellspacing="1" cellpadding="2" width="100%" border="0" class="pn-ftable">
<tbody>
<tr>
<td width="20%"></td>
<td width="80%" class="pn-fcontent">
<input type="file" name="pic" />
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="pn-fbutton" colspan="2">
<input type="submit" class="submit" value="提交"/> <input type="reset" class="reset" value="重置"/>
</td>
</tr>
</tbody>
</table>
</form>
</form>
2.配置springmvc-console.xml
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880"/>
</bean>
3.java代码
@RequestMapping("/uploadPicCt.do")
public void uploadPicCt(MultipartFile pic,HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{
if(pic != null && pic.getSize() > 0){
// 1、文件改名
String filename = pic.getOriginalFilename();
String suffix = FilenameUtils.getExtension(filename);
String uuid = UUID.randomUUID().toString().replace("-", "");
String newName = uuid + "." + suffix;
// 2、文件上传
String realPath = request.getServletContext().getRealPath(""); // 项目的真实路径
String imgUrl = "\\images\\" + newName; // 相对路径:用于jsp页面回显
String path = realPath + imgUrl;
pic.transferTo(new File(path));
// 3、响应json串
JSONObject jsonObject = new JSONObject();
jsonObject.put("imgUrl", imgUrl);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(jsonObject.toString());
}
}