因为一个项目要做一个头像上传的功能,因此选择了使用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;
}
}
												

jquery头像上传剪裁插件cropper的前后台demo的更多相关文章

  1. 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据

    1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...

  2. 使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能。并且在界面上有radio 的选择内容也要上传

    使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能.并且在界面上有radio 的选择内容也要上传 uploadify 插件的 下载和文档地址  ...

  3. 头像上传uploadPreview插件

    原文链接:https://blog.csdn.net/Alisa_L/article/details/52923953 uploadPreview 今天写头像上传,使用到uploadPreview插件 ...

  4. [Plugin] JQuery.uploadify上传文件插件的使用详解For ASP.NET

    URL:http://www.cnblogs.com/xiaopin/archive/2010/01/21/1653523.html 今天下午整理文件上传的例子,感觉收集到的例子都很不人性话,后来找到 ...

  5. C# Flash 图片上传案例(结合网上腾讯头像上传Flash插件)

    之前遇到过很多次要上传类似头像图片这种功能需求,这次是要求弄一个flash插件上传图片 感谢主,一个偶然机会在网上找到了一个很好的腾讯头像修改的flash插件:插件下载 这个功能采用Ajax访问支持, ...

  6. jquery uploadify上传文件插件导致浏览器崩溃问题解决方法

    自谷歌浏览器更新到(版本39.0.2171.99 )后,访问上传文件界面浏览器就崩溃了,而其他的浏览器不会出现问题. 出现这种问题的原因就是谷歌浏览器缓存问题,但将访问该jsp页面路径添加上时间戳后无 ...

  7. jquery文件上传版 插件

    /*! * jQuery Form Plugin * version: 4.2.2 * Requires jQuery v1.7.2 or later * Project repository: ht ...

  8. 强大的flash头像上传插件(支持旋转、拖拽、剪裁、生成缩略图等)

    今天介绍的这款flash上传头像功能非常强大,支持php,asp,jsp,asp.net 调用 头像剪裁,预览组件插件. 本组件需要安装Flash Player后才可使用,请从http://dl.pc ...

  9. 使用jquery插件uploadfive、jcrop实现头像上传

    1.html页面部分代码:(实现选着图片时,jcrop能够刷新图片) <script type="text/javascript"> $(function(){ $(& ...

随机推荐

  1. python基础(二)--多值参数以及类

    1.多值参数函数 def 函数名(*args , **kwargs): ....... 多值参数函数顾名思义能够传入多个参数,args表示传入的元组,kwargs表示传入的字典 def functio ...

  2. Raspberry U盘操作

    项目系统要求的对U盘分区,分出系统盘与用户盘.这就有了今天的这个总结了: 1.输入命令“fdisk -l”查看设备挂载的位置,因为这个在设备挂载的时候有可能会发生变化. 假设设备挂载到了 /dev/s ...

  3. 常见的浏览器兼容性问题与解决方案——CSS篇

    1.不同的浏览器的标签默认的外补丁和内补丁不同 问题症状:随便写几个标签,不加样式控制的情况下,各自的margin和padding差异较大. 碰到频率:100% 解决方案:初始化CSS的默认样式,*{ ...

  4. JavaScript中filter()方法

    方法概述 用于把数组(Array)的某些元素过滤掉,然后返回剩下的元素组成的数组. 语法: var filteredArray = array.filter(callback[, thisObject ...

  5. HTML 水平线hr

    HTML 水平线 <hr /> 标签在 HTML 页面中创建水平线. hr 元素可用于分隔内容. 实例 <p>This is a paragraph</p> < ...

  6. SQL UNION操作符使用

    SQL UNION 操作符 SQL UNION 操作符合并两个或多个 SELECT 语句的结果. SQL UNION 操作符 UNION 操作符用于合并两个或多个 SELECT 语句的结果集. 请注意 ...

  7. 爬虫入门之Scrapy框架基础框架结构及腾讯爬取(十)

    Scrapy终端是一个交互终端,我们可以在未启动spider的情况下尝试及调试代码,也可以用来测试XPath或CSS表达式,查看他们的工作方式,方便我们爬取的网页中提取的数据. 如果安装了 IPyth ...

  8. g++: error: unrecognized command line option ‘-std=C++11’

    一个小程序,在编译的时候出错,原来使用的编译命令是 g++ -std=C++11 array.cpp -o array.exe g++: error: unrecognized command lin ...

  9. 关于HiddenHttpMethodFilter

    这个类的代码比较少,所以把整个类的代码都复制过来.在注释中添加上自己的理解. public class HiddenHttpMethodFilter extends OncePerRequestFil ...

  10. SOJ4459 skysky's game(贪心+优先队列)

    天天最近迷上了天天爱消除游戏,现在他觉得这个游戏已经没有意思了.所以他发明一个新的消除游戏.有n堆糖果,每一个糖果有一个重量w,天天每次都选择两个糖果合并为一个糖果,新的糖果的重量等于这两个糖果的重量 ...