java,使用美图秀秀上传,设置头像
最近在倒弄个一个网站,www.thinkdee.com 没有完成,还在做,这里要用到用户头像设置,本来想自己处理的,看到网上美图功能太强大了,就试了一把!
美图开放平台:http://open.web.meitu.com/
开发文档:http://open.web.meitu.com/wiki/
头像设置示例:http://open.web.meitu.com/products/#M4
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>美图WEB开放平台</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://open.web.meitu.com/sources/xiuxiu.js" type="text/javascript"></script> <script type="text/javascript"> window.onload=function(){ xiuxiu.embedSWF("altContent",5,"100%","100%"); /*第1个参数是加载编辑器div容器,第2个参数是编辑器类型,第3个参数是div容器宽,第4个参数是div容器高*/ xiuxiu.setUploadType(2); xiuxiu.setUploadURL("${webRoot}/user/uploadface");//修改为您自己的上传接收图片程序 xiuxiu.onBeforeUpload = function(data, id){ xiuxiu.setUploadArgs({filetype: data.type, type: "image", filename: data.name }); } xiuxiu.onInit = function () { xiuxiu.loadPhoto("http://open.web.meitu.com/sources/images/1.jpg"); } xiuxiu.onUploadResponse = function(data) { if(data){ alert("头像设置成功"); location.href="${webRoot}/user/showuserinfo"; }else{ alert("头像设置失败"); } } } </script> <style type="text/css"> html, body { height:100%; overflow:hidden; } body { margin:0; } </style> </head> <body> <div id="altContent"> <h1>美图秀秀</h1> </div> </body> </html>
后台图片处理:
@RequestMapping("uploadface")
@ResponseBody
public boolean uploadface(HttpServletRequest request,HttpServletResponse response,@RequestParam("Filedata") MultipartFile file ) throws Exception{
if(!file.isEmpty()){
//得原始名字1.jpg
String originName = file.getOriginalFilename();
//取出.jpg
String fileType = originName.substring(originName.indexOf("."));
//生成新文件名 abc
String newFileName = UUIDGenerator.getUUID();
//生成abc.jpg
String newFile = newFileName + fileType;
//文件生成的路径-文件夹
// String uploadDir = MyWebUtil.getUploadHeadPath();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String datePath = sdf.format(new Date());
String rootPath = MyWebUtil.getWebRootPath();
String imgPath = "/upload/head/"+ datePath+"/";
String uploadDir = rootPath + imgPath ;
File f = new File(uploadDir);
if(!f.exists()){
f.mkdirs();
}
String toDiskPath = imgPath + newFile;
//生成的文件路径
String filePath = uploadDir + newFile;
byte[] bytes = file.getBytes();
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(bytes); //写入文件
//更新数据库
Subject subject = SecurityUtils.getSubject();
String logName = (String)subject.getPrincipal();
if(StringUtils.isNotBlank(logName)){
User u = userService.getByUserName(logName);
u.setUface(toDiskPath);
userService.updateUser(u);
}
//生成小图,中图头像
String mid = filePath +"-mid" +fileType;
String sml = filePath +"-sml" +fileType;
ScaleImage is = new ScaleImage();
is.saveImageAsJpg(filePath, sml, 30, 30);
is.saveImageAsJpg(filePath, mid, 60, 60);
return true;
}
return false;
}
浙公网安备 33010602011771号