一》吧上传图片方法提出来
public class UpPicture {
public static void upPicture(MultipartFile fl,HttpServletRequest req) throws Exception{
String path =req.getSession().getServletContext().getRealPath("/")+"upload/";
//真实路径
String fileName = fl.getOriginalFilename();
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
System.out.println(path);
//保存
try {
fl.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断文件大小
* @param fl
* @return
*/
public static Boolean size(MultipartFile fl){
// System.out.println(fl.length());
// 判断文件大小
long s = fl.getSize();
if (s>=2000000000) {
return false;
}
return true;
}
/**
* 判断图片格式
* @param flFileName
* @return
*/
public static Boolean geShi(String flFileName){
// 判断传入的是否为 图片
Set<String> set = UpPicture.imgSet();
Boolean b = false;
for (String s : set) {
if (flFileName.substring(flFileName.length()-3).equalsIgnoreCase((String) s)) {
b = true;
break;
}
}
return b;
}
/**
* 把常见的图片格式放入 set中
*
* @return
*/
public static Set imgSet() {// BMP、JPG、JPEG、PNG、GIF。
Set<String> set = new HashSet<>();
set.add("bmp");
set.add("jpg");
set.add("jpeg");
set.add("png");
set.add("gif");
return set;
}
}
二》controller层
/**
* 执行更新头像页面
* @return
*/
@RequestMapping("/do_editphoto.do")
@ResponseBody
public String doModiPhoto(Integer noid,MultipartFile file,HttpServletRequest request,Model model){
noid=1;
String fileFileName=file.getOriginalFilename();
boolean b=UpPicture.size(file) ;
if(!b ){
return "格式不对";
}
b= UpPicture.geShi(fileFileName);
if(!b){
return "格式不对";
}
try {
UpPicture.upPicture(file, request);
} catch (Exception e) {
return "error";
}
//保存路径是
String path="/family/upload/"+fileFileName;
userService.updatPhotoUrl(path,noid);
return path;
}
/**
* 切图上传图片
* @param x
* @param y
* @param w
* @param h
* @param fl
* @param session
* @return
*/
@RequestMapping("do_crop")
@ResponseBody
public String do_crop(String flName,String flFileName,Integer x,Integer y,Integer w,Integer h,HttpSession session){
if(x==null || y==null || w==null || h==null){
return "请稍候再试";
}
try{
ImageCut.cutImage(flFileName,x,y,w,h);
}catch(Exception e){
return "系统不太稳定哦";
}
// 获得session
Integer userId = (Integer)session.getAttribute("userId");
userId=1;
//保存路径是
String path=flName;
userService.updatPhotoUrl(path,userId);
return "ok";
}
三》jsp页面
<div id="firstDiv">
<form id="formImg">
<div>
<input type="hidden" name="noid" value="${noid }">
<span>更换头像:</span><br><br>
<input type="file" name="file" id="file"><br>
<a id="qclose" href="javascript:void(0)">显示裁剪预览图</a>
</div><br>
<!-- 裁剪图片 -->
<div id="qietu">
<img src="${photo}" id="hahahhah" />
<div id="preview-pane">
<div class="preview-container">
<img src="${photo}" id="targetss" class="jcrop-preview" alt="Preview" />
</div>
</div>
</div>
</form><br>
<div>
<form id="crop_form">
<input type="hidden" name="flName" value="${photo}"/>
<input type="hidden" name="flFileName" value="D:/tomcat8/tomcat8/webapps/${photo}"/>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<button type="button" id="crop_submit" class="btn btn-info" onclick="ajax_crop()">确认剪裁并保存</button>
</form>
</div>
</div>
</BODY>
<script type="text/javascript">
//切图进行上传
function ajax_crop(){
var url="${BasePath}/user/do_crop.do";
$("#crop_form").ajaxSubmit({
type:'post',
url:url,
clearForm:true,//清空所有表单元素的值
resetForm:true,//重置所有表单元素的值
success:function(STR){
if(STR=="ok"){
alert("修改成功");
window.location.reload();
}else{
alert("修改失败啦");
}
},
error:function(XmlHttpRequest,textStatus,errorThrown){
alert("上传失败了");
}
});
}
$("#qclose").click(function(){
$("#preview-pane").show();
})
//上传图片
$("#file").change(function (){
var url="${BasePath }/user/do_editphoto.do";
var files=$("#file").val();
if(files==null || files==""){
alert("不能为空哦");
return ;
}
$("#formImg").ajaxSubmit({
type:"post",
url:url,
success:function(str){
if(str=="error"){
alert("请稍后再试");
}else if(str=="格式不对"){
alert("格式不对");
}else{
window.location.reload();
}
},
error:function(XmlHttpRequest,textStatus,errorThrown){
alert("编辑失败了");
}
})
})
jQuery(function($){
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
console.log('init',[xsize,ysize]);
$('#hahahhah').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
// aspectRatio: xsize / ysize,
onRelease: clearCoords
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c){
if (parseInt(c.w) > 0){
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
console.log([c.x,c.y,c.w,c.h]);
$("#x").val(c.x);
$("#y").val(c.y);
$("#w").val(c.w);
$("#h").val(c.h);
};
function clearCoords(){
$('#coords input').val('');
};
});
</script>