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;
}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM