步骤如下:
(1)在html中定义1个form表单
<form id=”picForm” name=”picForm” action=”uploadPic.htm” enctype=”multipart/form-data” method=”post”>
<table>
<tr>
<td>
<label>图片:</label>
</td>
<td>
<input id="picUpload" name="picUpload" type="file">
</td>
</tr>
<tr>
<td colspan=”2″>
<input type="button" onclick="uploadPic();" value="上传">
</td>
</tr>
</table>
</form>
(2)定义js函数
function uploadPic(){
if($("#picUpload").val()==''){
alert("please select picture first!");
return;
}
var data = new FormData();
data.append('file', document.picForm.picUpload.files[0]);
$.ajax({
type: "POST",
url: "uploadPic.htm",
processData:false,
contentType:false,
data: data,
success: function (data) {
var obj = jQuery.parseJSON(data);
var result = obj.result;
if(result !="1"){
alert("Uploade file fail");
}
else{
alert("Uploade file succeed");
}
}
});
}
注意上面的document.picForm.picUpload.files[0],这里,javascript是通过name属性来找元素的。
(3)服务器端配置
在spring的配置文件里加入以下内容。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1000000"/>
</bean>
(4)服务器端代码
@Controller
public class MyController {
@RequestMapping("/uploadPic.htm")
@ResponseBody
public void uploadPic(ModelMap modelMap, HttpServletRequest req, HttpServletResponse res)
throws Exception {
JSONObject json = new JSONObject();
InputStream input = null;
OutputStream output = null;
try{
MultipartHttpServletRequest multipartReq = (MultipartHttpServletRequest) req;
MultipartFile rawFile = multipartReq.getFile("file");
String rawFilename = rawFile.getOriginalFilename();
String saveFileName = "d:\\"+rawFilename;
input = rawFile.getInputStream();
output = new BufferedOutputStream(new FileOutputStream(saveFileName));
byte[] buffer = new byte[1024];
int n = -1;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
json.put("result", 1);
res.setContentType("text/html;charset=utf-8");
res.getWriter().write(json.toString());
}
catch(Exception e){
json.put("result", 0);
res.setContentType("text/html;charset=utf-8");
res.getWriter().write(json.toString());
return;
}
finally{
input.close();
output.close();
}
}
}




