头像预览裁切上传案例

      发布在:前端技术      评论:0 条评论
<!--裁切使用cropperjs转成表单数据上传-->
<link rel="stylesheet" href="__STATIC__/js/cropper/cropper.min.css" />
<script src="__STATIC__/js/cropper/cropper.js"></script>
var $image = $('#image'),avatarObj=$('input[name="avatar"]'),uploderObj=$("#avatar_uploder"),fileObj, src,URL = window.URL || window.webkitURL,uploadedImageURL,isUpdate=0,dataBlob;

var options = {
minCanvasWidth: 100,
minCanvasHeight: 100,
maxCanvasWidth: 120,
maxCanvasHeight: 120,
minCropBoxWidth: 100,
minCropBoxHeight: 100,
minContainerWidth:260,minContainerHeight:280,maxContainerWidth:260,maxContainerHeight:280,
maxCropBoxWidth: 120,
maxCropBoxHeigh: 120,
aspectRatio: 1,
preview: '.img-preview',viewMode: 2,
crop: function (e) {
isUpdate=1;
console.log(e);
// result = $image.cropper('getCroppedCanvas',{fillColor: "#fff",height: 100,width: 100});
       // avatarObj.val(result.toDataURL('image/jpeg'));
     /*  $dataX.val(Math.round(e.detail.x));
       $dataY.val(Math.round(e.detail.y));
       $dataHeight.val(Math.round(e.detail.height));
       $dataWidth.val(Math.round(e.detail.width));
       $dataRotate.val(e.detail.rotate);
       $dataScaleX.val(e.detail.scaleX);
       $dataScaleY.val(e.detail.scaleY);*/
   }
};
$image.on({
ready: function (e) {
console.log(e.type);
},
cropstart: function (e) {
console.log(e.type, e.detail.action);
},
cropmove: function (e) {
console.log(e.type, e.detail.action);
},
cropend: function (e) {
console.log(e.type, e.detail.action);
},
crop: function (e) {
console.log(e.type);
},
zoom: function (e) {
console.log(e.type, e.detail.ratio);
}
}).cropper(options);
function update_avatar() {
if(isUpdate){
//获取裁切后的数据
       result = $image.cropper('getCroppedCanvas',{fillColor: "#fff",height: 100,width: 100});
dataURI=result.toDataURL('image/jpeg');
let byteString = atob(dataURI.split(',')[1]);
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var name=uploderObj.val();
if(name==''){name="{$user['avatar']}";}
dataBlob= new Blob([ab], {
type: mimeString
       });
//一定要修改文件名否则thinkphp验证文件后缀将报错
       var file = new File([dataBlob],name);
//创建formData对象
       var formData = new FormData();
//表单添加file文件字段
       formData.append('file', file);
//其他附带参数添加
       formData.append("isUpdate", isUpdate);
// src = $(".uploaded_res_box img").attr("src");
       $.ajax({
url: "{:url('Profile/avatarUpdate')}",
type: 'POST',
dataType:"json",
data: formData,
processData: false,// ⑧告诉jQuery不要去处理发送的数据
           contentType: false, // ⑨告诉jQuery不要去设置Content-Type请求头
           beforeSend: function () {
//⑩发送之前的动作
           },
success: function (data) {
console.log(data)
if (data.code == 1) {
reloadPage(window);
}else{
$.message({
message: data.msg,
time: '1000',
type: 'error',
onClose:function(){
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.responseText );//这里是详细的信息
           }
});
}else{
dialigCancel();
}
}
//图片上传预览+裁切功能
function avatar_upload(obj) {
if(URL.createObjectURL){
fileObj=uploderObj[0].files[0];
if (uploadedImageURL) {
URL.revokeObjectURL(uploadedImageURL);
}
var uploadedImageURL=URL.createObjectURL(fileObj);
$image.cropper('destroy').attr('src',uploadedImageURL).cropper(options);
}else if(window.FileReader){
fileObj=uploderObj[0].files[0];
var fr=new FileReader();
fr.onload=function () {
$image.cropper('destroy').attr('src',this.result).cropper(options);
}
fr.readAsDataURL(fileObj);
}else {
// 上传至服务器再返回图片预览地址
           Wind.use("ajaxfileupload", function () {
$.ajaxFileUpload({
url: "{:url('Profile/avatarUpload')}",
secureuri: false,
fileElementId: "avatar_uploder",
dataType: 'json',
data: {},
success: function (data, status) {
if (data.code == 1) {
src = "__ROOT__/upload/" + data.data.file;
$image.cropper('destroy').attr('src',src).cropper(options);
// $('.uploaded_file img,.uploaded_res_box img').attr('src',src);
                       } else {
$.message({
message: data.msg,
time: '1000',
type: 'error',
onClose:function(){
}
});
}

},
error: function (data, status, e) {
}
});
});
}
isUpdate=1;
return false;
}


相关文章
热门推荐