转自:http://www.programgo.com/article/28003253386/
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/Dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>上传照片</title>
<base href="/" target="_self" />
<jsp:directive.include file="/views/common/common_import.jsp" />
<script type="text/javascript">
$(document).ready(function() {
$("input[type='file']").change(function(evt) {
var files = evt.target.files;
for ( var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
$("#list img").attr("src", e.target.result); //预览图片的位置
};
})(f);
reader.readAsDataURL(f);
}
});
//提交表单
$("#uploadForm").ajaxForm(function() {
window.close();
});
});
</script>
</head>
<body>
<table style="width: 100%;">
<tr>
<td align="center"><br />
<div class="ModelTitleCss">上传照片</div></td>
</tr>
</table>
<br />
<form id="uploadForm" enctype="multipart/form-data" action="<%=request.getContextPath()%>/pilot/upPhoto.jspx" method="post">
<span style="padding-left: 15px; color: blue;">请从电脑上选择一张照片</span> <input type="hidden" id="pilotId" name="pilotId" /> <input type="file" id="photo" name="photo" />
<p></p>
<div id="list" align="center">
<img width="125" height="150" />
</div>
<p></p>
<div align="center">
<input type="submit" id="btm" value="上 传" class="ButCss" />
</div>
</form>
</body>
</html>
SpringMVC配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000" /> </bean>controller配置
@ResponseBody
@RequestMapping("/upPhoto")
public void upPhoto(MultipartHttpServletRequest request, String pilotId) throws IOException {
// 获得第1张图片(根据前台的name名称得到上传的文件)
MultipartFile file = request.getFile("photo");
// 获得文件名:
String filename = file.getOriginalFilename();
String imgtype = filename.substring(filename.lastIndexOf("."));
// 获取路径
String ctxPath = EnvironmentVariables.getValue(Constants.PHOTOS_PATH);
// 创建文件
File dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdir();
}
String pathname = ctxPath + pilotId + imgtype;// 存放路径
File uploadFile = new File(pathname);
FileCopyUtils.copy(file.getBytes(), uploadFile);
);
}