controller
@RequestMapping(value = "upload/uploadPortrait")
@ResponseBody
public JSONObject uploadUserImages(HttpServletRequest request,
@RequestParam("portrait") CommonsMultipartFile file) {
JSONObject json = new JSONObject();
String imgPath = "";
if (file != null) {
imgPath += file.getOriginalFilename();
String realPath = request.getSession().getServletContext()
.getRealPath("/upload");
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(realPath, file.getOriginalFilename()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json.put("imgPath", imgPath);
return json;
}
----------------------------------------------------------------------------------------
@RequestMapping(value = "upload/uploadPortrait")
@ResponseBody
public JSONObject uploadUserImages(HttpServletRequest request
) {
JSONObject json = new JSONObject();
String imgPath = "";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
.getFile("portrait");
if (file != null) {
imgPath += file.getOriginalFilename();
String realPath = request.getSession().getServletContext()
.getRealPath("/upload");
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(realPath, file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
}
json.put("imgPath", imgPath);
return json;
}
备注:两种写法,效果一样。
jsp页面
<script src="<%=path%>/scripts/ajaxupload.js"></script>
<script type="text/javascript">
$(function(){
var isCanSub = true;
if(!isCanSub){
return;
}
isCanSub = false;
/* 图片上传 */
var $e = $(".personal_jm_tx");
var $uploader = $("#-upload");
var $image = $e.find("img");
new AjaxUpload($uploader, {
name: 'portrait',
action: '<%=path%>/upload/uploadPortrait.do',
responseType: 'json',
onChange: function (file, extension) {
},
onSubmit: function (file, extension) {
//this.disable();
},
onComplete: function (file, response) {
$uploader.show();
if (response.success) {
$image.attr("src", response.userImageUrl);
} else {
$(".pop").css("display", "block");
isCanSub = true;
alert(response.imgPath);
var element = document.getElementById('zsImg');
element.src = "<%=path%>/upload/"+response.imgPath;
}
}
});
})
</script>
--------------------------------------------------------------------------------------------
<p><a href="#" id="-upload" style="display: block" class="shangchuan">[更换头像]</a></p>
<img id="zsImg" src="">
js名字是:ajaxupload.js