jquery头像上传剪裁插件cropper的前后台demo

因为一个项目要做一个头像上传的功能,因此选择了使用jquery的头像插件cropper,cropper是一款使用简单且功能强大的图片剪裁jQuery插件,但是在使用的时候,有一个很大的坑需要注意,那就是当上传的文件不需要转换成base64传输给后台的时候,使用FormData对象异步上传的时候,需要加上两个参数为false,此外还给除了两种上传头像的方式,一种直接上传到文件服务器,类似<input type="file" name="file"> 还有一种是将图片进行base64,在后台解密转换成图片。

contentType: false,

processData: false,

1.不进行base64转换直接上传后台

页面显示

<div class="up-img-cover" id="up-img-touch" >

    <img class="img-thumbnail" alt="点击图片上传" src="img/hu.jpg" th:src="${user.avatar}"
data-am-popover="{position:'left',content: '点击上传', trigger: 'hover focus'}" >
<div style="background:#F8F8FF;width:180px;position:absolute;height:26px;top:100px;left:24px;z-index: 2;text-align: center;opacity:0.8;" >
<span>修改头像</span>
</div>
</div>

此外附上代码(这里直接给出custom_up_img.js)的前端代码:

$(document).ready(function(){
$("#up-img-touch").click(function(){
$("#doc-modal-1").modal({width:'600px'});
});
});
$(function() {
'use strict';
// 初始化
var $image = $('#image');
$image.cropper({
aspectRatio: '1',
autoCropArea:0.8,
preview: '.up-pre-after',

});

// 事件代理绑定事件
$('.docs-buttons').on('click', '[data-method]', function() {

var $this = $(this);
var data = $this.data();
var result = $image.cropper(data.method, data.option, data.secondOption);
switch (data.method) {
case 'getCroppedCanvas':
if (result) {
// 显示 Modal
$('#cropped-modal').modal().find('.am-modal-bd').html(result);
$('#download').attr('href', result.toDataURL('image/jpeg'));
}
break;
}
});



// 上传图片
var $inputImage = $('#inputImage');
var URL = window.URL || window.webkitURL;
var blobURL;

if (URL) {
$inputImage.change(function () {
var files = this.files;
var file;

if (files && files.length) {
file = files[0];

if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
$image.one('built.cropper', function () {
// Revoke when load complete
URL.revokeObjectURL(blobURL);
}).cropper('reset').cropper('replace', blobURL);
$inputImage.val('');
} else {
window.alert('请选择图片!!!');
}
}

// Amazi UI 上传文件显示代码
var fileNames = '';
$.each(this.files, function() {
fileNames += '<span class="am-badge">' + this.name + '</span> ';
});
$('#file-list').html(fileNames);
});
} else {
$inputImage.prop('disabled', true).parent().addClass('disabled');
}

//绑定上传事件
$('#up-btn-ok').on('click',function(){
var $modal = $('#my-modal-loading');
var $modal_alert = $('#my-alert');
var img_src=$image.attr("src");
if(img_src==""){
set_alert_info("没有选择上传的图片");
$modal_alert.modal();
return false;
}

$modal.modal();
$("#image").cropper('getCroppedCanvas').toBlob(function(blob){
var formData = new FormData(); //这里创建FormData()对象
formData.append('file', blob); //给表单对象中添加一个name为file的文件 blod是这个插件选择文件后返回的文件对象
console.log(blob);
$.ajax({
url:"http://localhost:8081/file/upload", //这里我上传的是我自己开源的一个文件服务器 github地址:https://github.com/Admin1024Admin/FileServer.git
type: "POST",
data: formData,
contentType: false, //这里需要注意
processData: false,
success: function(data, textStatus){
$modal.modal('close');
set_alert_info(data.result);
$modal_alert.modal();
if(data.result=="ok"){
$("#up-img-touch img").attr("src",data.file);
var img_name=data.file.split('/')[2];
console.log(img_name);
alert("ok");
//异步更新头像地址
$.ajax({
url:"/space/"+url+"/updataAvatar",
type:"post",
data:{"imgUrl":data.file},
success:function (data) {
if(data=="ok"){
window.location.reload();
}
},
error:function () {
alert("更新失败");
}
})
window.location.reload();
}
},
error: function(){
$modal.modal('close');
set_alert_info("上传头像失败了!");
$modal_alert.modal();
//console.log('Upload error');
}
});
})
});

});

function rotateimgright() {
$("#image").cropper('rotate', 90);
}


function rotateimgleft() {
$("#image").cropper('rotate', -90);
}

function set_alert_info(content){
$("#alert_content").html(content);
}

后台代码:基于springboot

/**
 * 博客头像上传
* @param file
* @return
*/
@PostMapping("/file/upload")
@ResponseBody
public Map<String,Object> handleFileUpload(@RequestParam("file") MultipartFile file) {
File returnFile = null;
Map<String,Object> map = new HashMap<String,Object>();
try {
File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(),file.getBytes()); //需要注意,这里的File对象是我自定义的模型类。并非java.io.File对象
f.setMd5( MD5Util.getMD5(file.getInputStream()) );
returnFile = fileService.saveFile(f);
returnFile.setPath("http://localhost:8080/file/view/"+f.getId());
returnFile.setContent(null) ;
map.put("result","ok");
map.put("file","http://localhost:8081/file/view/"+f.getId());
return map;

} catch (IOException | NoSuchAlgorithmException ex) {
ex.printStackTrace();
map.put("result","no");
map.put("message",ex.getMessage());
return map;
}
}

2.转换成base64后传给后台,在后台解码保存图片

前端代码:

$(document).ready(function(){
$("#up-img-touch").click(function(){
$("#doc-modal-1").modal({width:'600px'});
});
});
$(function() {
'use strict';
// 初始化
var $image = $('#image');
$image.cropper({
aspectRatio: '1',
autoCropArea:0.8,
preview: '.up-pre-after',

});

// 事件代理绑定事件
$('.docs-buttons').on('click', '[data-method]', function() {

var $this = $(this);
var data = $this.data();
var result = $image.cropper(data.method, data.option, data.secondOption);
switch (data.method) {
case 'getCroppedCanvas':
if (result) {
// 显示 Modal
$('#cropped-modal').modal().find('.am-modal-bd').html(result);
$('#download').attr('href', result.toDataURL('image/jpeg'));
}
break;
}
});



// 上传图片
var $inputImage = $('#inputImage');
var URL = window.URL || window.webkitURL;
var blobURL;

if (URL) {
$inputImage.change(function () {
var files = this.files;
var file;

if (files && files.length) {
file = files[0];

if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
$image.one('built.cropper', function () {
// Revoke when load complete
URL.revokeObjectURL(blobURL);
}).cropper('reset').cropper('replace', blobURL);
$inputImage.val('');
} else {
window.alert('请选择图片!!!');
}
}

// Amazi UI 上传文件显示代码
var fileNames = '';
$.each(this.files, function() {
fileNames += '<span class="am-badge">' + this.name + '</span> ';
});
$('#file-list').html(fileNames);
});
} else {
$inputImage.prop('disabled', true).parent().addClass('disabled');
}

//绑定上传事件
$('#up-btn-ok').on('click',function(){
var $modal = $('#my-modal-loading');
var $modal_alert = $('#my-alert');
var img_src=$image.attr("src");
if(img_src==""){
set_alert_info("没有选择上传的图片");
$modal_alert.modal();
return false;
}

$modal.modal();
var url=$(this).attr("imgurl");
var canvas=$("#image").cropper('getCroppedCanvas'); //获取到图片转换成的canvas对象
var data=canvas.toDataURL(); //将图片转成base64
$.ajax({
url:"http://localhost:8081/file/upload",
type: "POST",
data: {"img":data.toString}, //这里传递参数给后台
success: function(data, textStatus){
$modal.modal('close');
set_alert_info(data.result);
$modal_alert.modal();
if(data.result=="ok"){
$("#up-img-touch img").attr("src",data.file);
var img_name=data.file.split('/')[2];
console.log(img_name);
alert("ok");
window.location.reload();
}
},
error: function(){
$modal.modal('close');
set_alert_info("上传头像失败了!");
$modal_alert.modal();
//console.log('Upload error');
}
});

});

});

function rotateimgright() {
$("#image").cropper('rotate', 90);
}


function rotateimgleft() {
$("#image").cropper('rotate', -90);
}

function set_alert_info(content){
$("#alert_content").html(content);
}

后台base64解码代码:

/**
 * 头像上传
*/
@PostMapping("/{username}/avatar")
@ResponseBody
public Map<String,Object> uploadAvatar(@RequestParam("image")String image){
String imgBase64 = image.replace("data:image/png;base64,","");
boolean b = GenerateImage(imgBase64);
System.out.println("保存成功---->"+b);
Map<String,Object> map = new HashMap<String,Object>();
map.put("result","ok");
map.put("file","图片路径");
return map;
}
//base64字符串转化成图片   
public boolean GenerateImage(String imgStr){
//对字节数组字符串进行Base64解码并生成图片       
if (imgStr == null) { //图像数据为空           
return false;
}
try{
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码           
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0){//调整异常数据                   
b[i]+=256;
}
}
//生成jpeg图片           
String imgFilePath = "D:\\images\\new.jpg";//新生成的图片           
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e){
return false;
}
}


猜你喜欢

转载自www.cnblogs.com/l024/p/9714176.html
今日推荐