cropper配合ajaxupload实现图片截图与上传并上传至远程服务器地址
1、插件引用
<!-- 上传图片css -->
<link rel="stylesheet" href="../css/common/cropper.min.css" />
<!-- 图片上传插件 -->
<script src="../js/common/ajaxupload.js" type="text/javascript"></script>
<!-- 截图插件cropper -->
<script src="../js/common/cropper.min.js" type="text/javascript"></script>
2、html代码
<!-- 图片剪裁工具 -->
<div class="a-img">
<div id="show_FormatImg" style="width: 400px; height:200px;display: none;">
<button type="button" class="close" id="btn_delFormatImg" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<img alt="头像" id="a_formatImg" src="" />
</div>
<input type="image" id="uploadImg" src="../img/btn_pic.png"><br />
<span class="i-msg">点击添加或者更改图片</span>
<div id="upload_img" class="row" style="display: none;">
<div class="col-sm-12">
<div style="width: 400px; height: 200px; margin: 0 auto;">
<img id="image_upload" class="img-responsive" src="###" />
</div>
<div style="margin-top: 15px;">
<button id="btn_uploadImg" type="button" class="btn btn-primary" style="background-color: #686897; color: #FFFFFF;">确定</button>
<button id="btn_cancel" type="button" class="btn btn-primary" style="background-color: #686897; color: #FFFFFF;">取消</button>
</div>
</div>
</div>
</div>
3、js代码:
初始化变量:
/**
* 默认参数
*/
defaultOption: {
img:"", //新增图片名称
flag_uploadImg:true,// 防止重复上传图片
}
第一步:图片上传与回显:
/**
* 上传图片
* @returns
*/
uploadimg:function(){
var index;
var button = $('#uploadImg');
new AjaxUpload(button,{
action: '../upload/uploadImg.do',
name: 'img',
onSubmit : function(file, ext){
if (ext && /^(jpg|JPG|jpeg|JPEG|png|PNG|gif|bmp)$/.test(ext)){
// 开启加载层
index = layer.load(2, {
shade: [0.1,'#fff'] //0.1透明度的白色背景
});
return true;
} else {
layer.msg('非图片类型文件,请重传!');
return false;
}
},
onComplete: function(file, result){ //上传完毕后的操作
layer.close(index); // 关闭加载层
$('#uploadImg').hide();
$('.i-msg').hide();
var imgurl = '../upload/'+result;
$('#image_upload').attr('src',imgurl);
$('#upload_img').show();
banner.initCropper();
}
});
},
第二步:剪裁插件cropper初始化:
/**
* 剪裁图片初始化
*/
initCropper:function(){
var banner_group=banner.defaultOption.banner_group;
var source_type=banner.defaultOption.source_type;
if(banner_group==0||source_type==2){
// 初始化上传图片
$('#image_upload').cropper({
aspectRatio : 4.2 / 1,
autoCropArea : 1,
movable : false,
zoomable : false,
rotatable : false,
scalable : false
});
}else if(source_type==0||source_type==1||source_type==3||source_type==4){
// 初始化上传图片
$('#image_upload').cropper({
aspectRatio : 2.17 / 1,
autoCropArea : 1,
movable : false,
zoomable : false,
rotatable : false,
scalable : false
});
}else{
layer.alert("请先选择轮播图需要配置的页面")
$('#a_formatImg').attr("src",'');
$('#a_formatImg').attr("url",'');
$('#show_FormatImg').hide();
$('#upload_img').hide();
$('#uploadImg').show();
$('.i-msg').show();
}
}
第三步:对剪裁后的图片再进行base64格式的文件上传、
// 上传图片确认按钮
$('#btn_uploadImg').click(function(){
// 开启加载层
var index = layer.load(2, {
shade: [0.1,'#fff'] //0.1透明度的白色背景
});
if(banner.defaultOption.flag_uploadImg){
banner.defaultOption.flag_uploadImg = false;// 防止重复保存图片
$('#upload_img').hide();
//获取剪裁区域的图像src并转为base64
var dataurl = $('#image_upload').cropper("getCroppedCanvas","").toDataURL('image/png');
$('#image_upload').cropper("destroy");//清空图片
var map = new Object();
map.img = dataurl;
commonAjax.ajaxSubmit("banner/upPic.do",map,function(result) {
if(result.resCode==0){
banner.defaultOption.flag_uploadImg = true;
layer.close(index); // 关闭加载层
if (result.resCode==0) {
var data = result.resData;
banner.defaultOption.img=data;
var imgurl = commonAjax.defaultOption.imgurl+commonAjax.defaultOption.sp_banner_img+data;
$('#upload_img').hide();
$('#a_formatImg').attr('src',imgurl);
$('#a_formatIm g').attr('url',data);
$('#show_FormatImg').show();
}else{
if(result.errCode == "1002"){
if(window.top==window.self){//不存在父页面
window.location.href = "login.html";
}else{
parent.gotoLoginHtml();
}
}else{
layer.msg('发生未知错误,我们正在努力解决中!');
}
}
}else{
layer.msg("获取数据失败")
}
});
}
});
4、后台代码块
(一)第一次图片上传与回显代码
@RequestMapping("/uploadImg")
public String uploadImg(HttpSession session,@RequestParam("img") CommonsMultipartFile mFile){
log.info(GlobalContract.LOG_BEGIN);
String result = "";
try {
// 从session获取登入者信息
UserRVO user = (UserRVO) session.getAttribute("sysuser");
if(user != null){
// 1.图片保存到本地
String fileName = mFile.getFileItem().getName();
// 图片后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 修改后的文件名
fileName =String.valueOf("s"+String.valueOf(System.currentTimeMillis()).concat(suffix.toLowerCase()));
// 图片路径
String filePath = session.getServletContext().getRealPath("/upload/");
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(filePath.concat(File.separator).concat(fileName));
mFile.getFileItem().write(file);
result = fileName;
}else{
result = JSONObject.fromObject(new ResultVO("1002")).toString();
}
} catch (Exception e) {
result = GlobalContract.ERROR_RESULT;
log.error(e.getMessage());
e.printStackTrace();
}
log.info(GlobalContract.LOG_END);
return result;
}
(二)文件截取后第二次上传并上传至远程服务器
@RequestMapping("/upPic")
public String upPic(HttpSession session,
@RequestBody Map<String, String> map){
log.info(GlobalContract.LOG_BEGIN);
ResultVO resultVO = null;
if (SessionUtil.isOnSession(session)) {
// 处理照片
String img_base64 = map.get("img"); // 获取图片base64
// 图片保存路径
String filePath = "d://IMGNFS/ejyshop_temp/".concat("/sp_banner_img/");
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
String fileFormat = ".".concat(img_base64.substring(11, img_base64.indexOf(";")));
String fileData = img_base64.substring(img_base64.indexOf(",")+1);
String fileName = "s"+String.valueOf(System.currentTimeMillis()).concat(fileFormat);
try {
// 保存文件到本地
Base64Util.decodeFile(fileData, filePath.concat(fileName));
// 2.上传图片到服务器
List<String> list = new ArrayList<String>(1);
list.add(filePath.concat(fileName));
String result_file = "";
result_file = HttpClientUtil.postFile(list, "/sp_banner_img/");
if(result_file != null && !result_file.isEmpty()) {
// 返回图片名
resultVO = new ResultVO();
resultVO.setResData(fileName);
}else{
resultVO = new ResultVO("1001");
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
resultVO = new ResultVO("1002");
}
log.info(GlobalContract.LOG_END);
return JSONObject.fromObject(resultVO).toString();
}
(三)工具类
1、Base64Util.decodeFile文件上传方法
/**
* 对文件进行解码
* @param oldString 需要解码的字符串
* @param filePath 将字符串解码到filepath文件路径
* @return 返回解码后得到的文件
* @throws Exception
*/
public static void decodeFile(String fileString, String filePath) throws Exception{
File file = new File(filePath);
if(file.exists()){
file.delete();
}
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
byte[] debytes = null;
if (fileString != null) {
debytes = new Base64().decode(fileString.getBytes());
}
out.write(debytes);
out.close();
}
2、HttpClientUtil.postFile上传至远程服务器方法
/**
* 上传文件
* @param filePathList 文件路径
* @param filePath 在文件服务器 保存的文件夹名 例:“/poi_thumbnail/”
* @throws ParseException
* @throws IOException
*/
public static String postFile(List<String> filePathList, String filePath)
throws ParseException, IOException {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
MultipartEntityBuilder build = MultipartEntityBuilder.create();
build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
build.setCharset(CharsetUtils.get("UTF-8"));
for (int i = 0; i < filePathList.size(); i++) {
build.addPart("uploadFile" + i,
new FileBody(new File(filePathList.get(i))));
}
build.addPart(
"filePath",
new StringBody(filePath, ContentType.create("text/plain",
Consts.UTF_8)));
// 把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost("http://121.40.97.206:9010/fileServer-web/fileUpload/upload");
// 以浏览器兼容模式运行,防止文件名乱码。
HttpEntity reqEntity = build.build();
httpPost.setEntity(reqEntity);
//System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 打印响应状态
//System.out.println(response.getStatusLine());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应长度
//System.out.println("Response content length: "
// + resEntity.getContentLength());
// 打印响应内容
//System.out.println(EntityUtils.toString(resEntity,
// Charset.forName("UTF-8")));
result = EntityUtils.toString(resEntity,
Charset.forName("UTF-8"));
}
// 销毁
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpClient.close();
}
return result;
}
3、代码中间的常量
public enum HttpMultipartMode {
/** RFC 822, RFC 2045, RFC 2046 compliant */
STRICT,
/** browser-compatible mode, i.e. only write Content-Disposition; use content charset */
BROWSER_COMPATIBLE,
/** RFC 6532 compliant */
RFC6532
}