1.首先要设置crossdomain.xml
下载地址:https://download.csdn.net/download/ly_linyuan/10355995
这个要特别注意,要把这个文件下载下来之后直接放在根目录下面,比如D盘或者某个盘根目录下, 通过访问地址:(本机ip/crossdomain.xml)要直到你在浏览器能访问到。我这里是在自己电脑的D盘下,(访问地址:http://localhost:8080/crossdomain.xml)
2.在页面引入js
3.在页面初始化以及进行设置
4.完整页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>美图秀秀上传头像</title>
<script src="${path}/js/jquery1.42.min.js" type="text/javascript"></script>
<!-- 美图秀秀 -->
<script src="http://open.web.meitu.com/sources/xiuxiu.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
var url = "http://localhost:8080/personal/user/uploadPic";
$(function(){
/*第1个参数是加载编辑器div容器,第2个参数是编辑器类型,第3个参数是div容器宽,第4个参数是div容器高*/
xiuxiu.embedSWF("altContent",5,850,500);
//修改为自己的图片上传接口
xiuxiu.setUploadURL(url);
xiuxiu.setUploadType(2);
xiuxiu.setUploadDataFieldName("file");
xiuxiu.onUploadResponse = function (data){
if(data=="1"){
alert("保存成功!");
}else{
alert("保存失败,请重试")
}
location.reload();
};
})
</script>
<body>
<div class="tophide" style="display:block;" id="div1">
<center><h3>头像上传</h3>
<div class="headbox" id="altContent">
</div></center>
</div>
</body>
</html>
5.效果图:
6.后台上传图片代码:
/**
* 上传头像
* @return
*/
@RequestMapping("/uploadPic")
@ResponseBody
public String saveFile(MultipartFile file,HttpSession session) {
//判断文件是否为空
if(file !=null){
Integer uid = (Integer) session.getAttribute(Constant.SESSION_ACCOUNTID);
User user = userService.getUserById(uid);
//获取文件名
String fileName=file.getOriginalFilename();
//apache图片资源访问的路径(这里是我自己在配置文件中配置的)自己可以用下面的路径
/*String path = DeployProperties.getInstance().getProperty("PATH");
String url = DeployProperties.getInstance().getProperty("APACHE_URL");*/
//apache图片资源访问的路径,可以直接写,headPic是我上传头像的保存目录
String path= "http://localhost:8080/headPic";
//文件名后缀
try {
String type = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//美图秀秀插件已经过滤了上传的文件格式,此处不用判断
//保存到服务器上的文件名
String trueFileName=String.valueOf(System.currentTimeMillis())+type;
/*//保存到服务器上的地址
String realPath=path+"/"+trueFileName;
//保存到服务器上
file.transferTo(new File(realPath));*/
//对外访问的路径
String picUrl=path+"/"+trueFileName;
user.setHeadPic(picUrl);
//图片上传后保存的目录和名称
file.transferTo(new File("D:\\headPic\\" + trueFileName));
//保存到数据库中
userService.update(user);
return "1"; //自定义成功的标志
} catch (Exception e) {
log.error("上传图片错误:" + e.getMessage());
}
}
return "2"; //自定义失败的标志
}
注意:这里的String path= “http://localhost:8080/headPic“中的headPic是在eclipse中配置的访问图片上传后保存在本地文件的path路径,配置方法详见:https://blog.csdn.net/ly_linyuan/article/details/79981925
7.演示: