前台
<div id="personPhoto" name="personPhoto" class="col-sm-1" style="height: 150px;width: 120px;" align="center" onclick="photoUpload();" >
<img style="width:120px;height:150px" src="../img/facePic.png" alt="照片" /></div>
<script>
function photoUpload(){
layer.open({
type: 2,
title: '上传',
area: [500, 300],
fix: false, //不固定
maxmin: false,
content: "${pageContext.request.contextPath}/lab/aadaoruExcl.do?method=doUpload"
});
}</script>
弹出的上传图片框
<script src="<c:url value="/javascript/ajaxfileupload.js" />" type="text/javascript"></script>
<script>
function ajaxFileUpload() {
if($("#photoFile").val() != ""){
$.ajaxFileUpload({
url: '${pageContext.request.contextPath}/lab/aadaoruExcl.do?method=saveUploadPic', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'photoFile', //文件上传域的ID
dataType: 'json', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
parent.setPhoto(data.base64Code);
parent.layer.close(index);
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
}
}
</script>
</head>
<body>
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title" >
<div align="center">
<div><label class="col-sm-1 control-label"></label></div>
<p><input type="file" id="photoFile" name="photoFile" /></p>
<button class="btn btn-success" onclick="ajaxFileUpload()" >上传</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
ajaxFileUpload将图片提交到后台转码
@RequestMapping(params = "method=saveUploadPic", method = {RequestMethod.POST,RequestMethod.GET})
public void saveUploadPic(Model model,HttpServletRequest request,HttpServletResponse response
,@RequestParam(value = "photoFile", required = false) MultipartFile file
)throws Exception{
Gson gson = new Gson();
Map map = new HashMap();
PrintWriter out= response.getWriter();
String base64Code = "";
BASE64Encoder encoder = new BASE64Encoder();
byte[] data = null;
InputStream in = file.getInputStream();
data = new byte[in.available()];
in.read(data);
in.close();
base64Code = encoder.encode(data);
map.put("base64Code", base64Code);
out.print(gson.toJson(map));
}
前台img标签接收
function setPhoto(str){
$("#photo").val(str);
$("#personPhoto").html('<img style="width:120px;height:150px" src=\'data:image/jpg;base64,'+str+'\' />');
}