涉及到new FileReader()、new File()、new FormData()、createObjectURL() 上传 压缩
FormData js模拟表单上传
var formData = new FormData();
formData.append("type","2");
formData.append("file",blob,"recorder.mp3"); //添加上传blob数据类型
formData.append("file",file,"1.jpg"); //添加上传file数据类型
$('#xx').click(function () {
$.ajax({
beforeSend:function(e){
var type='(jpg|png)'
if( !(new RegExp(".+\."+type+"$",'ig').test( $('#file')[0].files[0].name ) ) ){
layer.msg('文件类型不正确');
_this.val('')
return false
}
},
url:"/uploadbase64" //上传接口地址
,type:"POST"
,contentType:false //让xhr自动处理Content-Type header,multipart/form-data需要生成随机的boundary
,processData:false //不要处理data,让xhr自动处理
,data:formData
,success:function(v){
console.log("上传成功",v);
}
,error:function(s){
console.error("上传失败",s);
}
});
});
//多文件上传
<input id="file" type="file" name="uploads" multiple="multiple" onchange="cb()"><br>
function cb(){
for(let i=0;i<$('#file')[0].files.length;i++){
//
sendfild(i)
}
function sendfild(x){
formData = new FormData();
formData.append("uploads",$('#file')[0].files[x],$('#file')[0].files[x].name); //添加上传file数据类型name
$.ajax({
beforeSend:function(e){
// var type='(jpg|png)'
// if( !(new RegExp(".+\."+type+"$",'ig').test( $('#file')[0].files[0].name ) ) ){
// layer.msg('文件类型不正确');
// _this.val('')
// return false
// }
},
url:"/upload" //上传接口地址
,type:"POST"
,contentType:false //让xhr自动处理Content-Type header,multipart/form-data需要生成随机的boundary
,processData:false //不要处理data,让xhr自动处理
,data:formData
,success:function(v){
console.log("上传成功",v);
// sendfild(x)
}
,error:function(s){
console.error("上传失败",s);
}
})
}
return false
}
file 转 base64 (FileReader方法)
<input id="fielinput" type="file" multiple="multiple" accept="image/*" onchange="showPreview(this)">
function showPreview(source) {
var file = source.files[0];
//判断文件类型
var extfile = file.name;
var AllImgExt=".jpg|.jpeg|.gif|.bmp|.png|";
var extName = extfile.substring(extfile.lastIndexOf(".")).toLowerCase();//(把路径中的所有字母全部转换为小写)
if(AllImgExt.indexOf(extName+"|")==-1)
{
var ErrMsg="该文件类型不允许上传。请上传 "+AllImgExt+" 类型的文件,当前文件类型为"+extName;
alert(ErrMsg);
return false;
}
if(window.FileReader) {
var fr = new FileReader();
fr.readAsDataURL(file);
fr.onloadend = function(e) {
// e.target.result base64
document.getElementById("fielImg").src = e.target.result;
// document.getElementById("baseimg").value = e.target.result;
// console.log(convertBase64UrlToBlob(e.target.result));
};
}else{
alert('浏览器不支持预览图片');
}
};
图片 转 base64 (canvas的toDataURL方法)
*注意toDataURL方法会涉及到跨域问题,要让后台对图片链接的处理
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var image = new Image();
image.crossOrigin = '';
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image); //这里获取base64
}
base64 转 file
function base64URLtoFile(base64Data, filename) { //*filename包括后缀名,例如1.png
var arr = base64Data.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
}
blob转json
const reader = new FileReader();
reader.readAsText(blobData, 'utf-8');
reader.onload = function (e) {
const readerres = reader.result;
const parseObj = JSON.parse(readerres);
}
base64 转 blob
function convertBase64UrlToBlob(urlData){
var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ab] , {type : 'image/png'});
}
file 转 blob (createObjectURL方法)
或者file转base64在转blob
url地址转base64
url地址转file对象
var img =
"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=508387608,2848974022&fm=26&gp=0.jpg"; //imgurl 就是你的图片路径
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
var image = new Image();
image.src = img;
image.setAttribute("crossOrigin", "Anonymous");
image.onload = function() {
var base64 = getBase64Image(image);
console.log(base64);
document.getElementById("img").src = base64;
var formData = new FormData();
//转换base64到file
var file = btof(base64, "test");
formData.append("imageName", file);
};
function btof(data, fileName) {
const dataArr = data.split(",");
const byteString = atob(dataArr[1]);
const options = {
type: "image/jpeg",
endings: "native"
};
const u8Arr = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
u8Arr[i] = byteString.charCodeAt(i);
}
return new File([u8Arr], fileName + ".jpg", options);
}
数据类型上传
file:直接上传,就是我们平时用的<input type=”file”>
base64:直接传,但需要将data:image/png;base64,这段内容过滤掉,后台才能转为成 图片,
blob:需要转成file类型,可以利用new FormData()
上传还需要涉及到 《post发送数据时的两种编码格式》
前端压缩图片并上传
(1)图片转blob
(2)图片转base64位
———————————–
<script src="js/exif.js"></script>
<div class="IDcardA"><input id="zm" @change="getImageBase64($event, 'IDcardA')" type="file" accept="image/*"></div>
<div class="IDcardB"><input id="fm" @change="getImageBase64($event, 'IDcardB')" type="file" accept="image/*"></div>
function rotateImg(img, step, canvas) {
//最小与最大旋转方向,图片旋转4次后回到原方向
var min_step = 0;
var max_step = 3;
if (img === null) return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
var height = img.height;
var width = img.width;
//旋转角度以弧度值为参数
var degree = step * 90 * Math.PI / 180;
var ctx = canvas.getContext('2d');
switch (step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0);
break;
}
return canvas;
}
methods:{
getImageBase64: function(e, className) {
var self = this;
// self.jsOpenCamear();
var el = e.target;
var imgBase64 = '';
if(!el.files || !el.files.length){
return;
}
var file = el.files[0];
if (/\.txt/.test(file.name) || !file.size) {
Tools.loading(false);
return Tools.dialog.alert('请拍照或者上传图片!');
}
Tools.loading(true);
EXIF.getData(file, function() {
self.orientation = EXIF.getTag(file, 'Orientation');
});
var fileName = file.name;
var reader = new FileReader();
//读取文件以数据URI的形式保存在reader的result属性中
reader.readAsDataURL(file);
//获取图片大小,以M为单位
var fileSize = Math.round(file.size / 1024 / 1024);
//获取图片大小,以KB为单位
var fileSizeKB = Math.round(file.size / 1024);
//上传图片的尺寸必需大于200KB
if (fileSizeKB > 1024) {
// Tools.dialog.alert('请上传1MB以内的图片', '好的');
// return;
}
el.value = '';
reader.onload = function () {
var cvs = document.createElement("canvas");
var img = new Image();
img.src = this.result;
img.onload = function() {
var width = img.width, height = img.height;
switch (cvs.width = width,
cvs.height = height,
self.orientation) {
case 3:
cvs = rotateImg(this, 2, cvs);
break;
case 6:
cvs = rotateImg(this, 1, cvs);
break;
case 8:
cvs = rotateImg(this, 3, cvs);
break;
default:
cvs = rotateImg(this, 0, cvs);
}
var imgData = cvs.toDataURL('image/png');
if (fileSizeKB > 60) {
compress(imgData, fileSize, 1024, fileName, function(imgBase64Data, fileName){
imgBase64 = imgBase64Data;
imgBase64 = imgBase64Data.replace(/data:image\/(png|jpeg|jpg|gif);base64,/g,'');
Tools.loading(false);
self.uploadProfile(imgBase64, className);
},'', 0.6);
} else {
Tools.loading(false);
imgBase64 = imgData;
imgBase64 = imgData.replace(/data:image\/(png|jpeg|jpg|gif);base64,/g,'');
self.uploadProfile(imgBase64, className);
}
};
//获取原图的base64信息
};
},
/*预览*/
previewPic: function(imageUrl, className) {
if (className == 'IDcardA') {
imageIdcardFront=imageUrl;
$('.positive').css({background:'#EEF0F1 url('+imageUrl+') no-repeat center',backgroundSize:'contain'}).find('.dele-img').show();
} else if (className == 'IDcardB') {
$('.back').css({background:'#EEF0F1 url('+imageUrl+') no-repeat center',backgroundSize:'contain'}).find('.dele-img').show();
imageIdcardBack=imageUrl;
}
// $('.'+className).css({
// 'background': 'url('+imageUrl+') no-repeat',
// 'background-size': 'contain',
// 'border': 'dashed .05rem #ccc',
// 'border-radius': '.3rem'
// });
},
// 上传照片到后台
uploadProfile: function(imgBase64, className) {
var self = this;
if (!imgBase64) {
return Tools.dialog.alert('当前图片不合格,请换一张试试!');
}
Tools.loading(true);
//-----------需要后台能接收到base64的数据类型并生成图片---------------------
$.ajax({
// xhrFields:{
// withCredentials:true
// },
// crossDomain:true,
type: 'post',
data: JSON.stringify({
strFiles: imgBase64
}),
contentType: "application/json",
dataType: "json",
url: ajaxUrl,
timeout: 60000,
headers:{
"userToken": sessionStorage.getItem('userToken')
},
complete: function(x, t) {
if(typeof completeFn == 'function'){
completeFn(x, t);
} else {
if(Tools && Tools.loading){
Tools.loading(false);
}
}
},
success:function (res) {
self.previewPic(res.data, className);
},
error:function (res) {
}
});
//--------------------------------
},
} //methods