Controller层代码
@RequestMapping("/savePic")
@ResponseBody
public String savePic(@RequestParam(value = "file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 文件保存路径
String path = request.getSession().getServletContext().getRealPath("");
System.err.println(path);
path = path.replaceAll("proxy_manage", ""); //proxy_manage 为项目名称
System.err.println(path);
path = path.substring(0, path.length() - 1);
System.out.println(path);
File newFile = new File(path + "images/student/"); //为图片文件夹下的图片存放文件夹目录
if (!newFile.exists())
newFile.mkdirs();
String name = file.getOriginalFilename();
String wei = name.substring(name.lastIndexOf("."), name.length());
String uuid = UUID.randomUUID().toString();
String filePath = path + "images/student/" + uuid + wei;
// 转存文件
file.transferTo(new File(filePath));
// // img路径
// String imgUrl = ImagUtils.imgUrl();
return "/student/" + uuid + wei;
} catch (Exception e) {
e.printStackTrace();
}
}
return "err";
}
JSP页面
<div
style="width: 207px; height: 214px; border: 1px solid #95B8E7; margin: 0px 0px 11px 191px;position: relative"
class="picture_div" id="picture">
<h4 style="text-align: center; color: #6d88ac">学生照片</h4>
<input style="width: 180px; height: 40px" class="easyui-filebox"
name="file3" buttonIcon="icon-man" buttonAlign="right" id="files3"
buttonText="添加" data-options="prompt:'请选择文件...'" /> <img alt="图片"
style="width: 100%; height: 212px; margin: 0 auto; display: none"
id="img3">
<img alt="" src="static/images/cuo3.png"
class="ccd"
style="position: absolute; top: 0px; right: 0px; width: 30px; display: none">
</div>
JS
var imgurl = '<%=resource.getString("image_url")%>';
//照片回显
$('#files3').filebox({
onChange: function(value) {
if(value!='' && value != null){
var formData = new FormData();
formData.append('file',$('#filebox_file_id_4').get(0).files[0]);
$.ajax({
url :"student/savePic",
type :'POST',
data : formData,
cache: false,
processData: false,
contentType: false ,
success:function(data) {
$('#img3').attr('src',imgurl+data);
$('#student_Pic').textbox("setValue",data);
$('#picture img').siblings().css('display','none');
$('#picture img').css('display','block');
},
});
}
}
})
//删除图片
$('.ccd').click(function (){
var index1=$(this).parent().index('.picture_div');
if(index1==0){
$('#files3').textbox('setValue','');
$('#picture').children().css('display','block');
$('#student_Pic').textbox("setValue","");
$('#picture img').css('display','none');
$('#files3').css('display','none');
}
})
效果