阿里OSS图片存储以及图片压缩
2018-10-27 本文已影响113人
饥人谷_米弥轮
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="aliyunOSS/aliyun-oss-sdk.js"></script>
<title></title>
</head>
<body>
<input type="file" id="file" multiple="multiple" />
<script>
//阿里云服务器对象
var client = new OSS({
region: 'oss-cn-shenzhen',
accessKeyId: 'xxxxx', //阿里OSS信息
accessKeySecret: 'xxxxxxx', //阿里OSS信息
bucket: 'avic-paixiu-2019',
secure: true //是否开启HTTPS
});
// 获取图片input选取的图片信息
function fileChange(e) {
let reader = new FileReader(); //异步读取计算机文件信息
let file = e.target.files[0];
let name = e.target.files[0].name
let imgFile;
reader.readAsDataURL(file);
reader.onload = function (e) {
imgFile = e.target.result;
this.getImgToBase64(imgFile, function (data) {
var myFile = dataURLtoFile(data, name);
this.submit(myFile)
}, 400, 400);
};
}
// 使用canvas压缩图片并转换base64
function getImgToBase64(url, callback, width, height, ratio) {
//将图片转换为Base64并压缩
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
canvas.height = width; //转换图片像素大小
canvas.width = height;
ctx.drawImage(img, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/png", ratio); //通过canvas获取图片的base64的URL
callback(dataURL);
canvas = null;
};
img.src = url;
}
// base64转换文件
function dataURLtoFile(dataurl, filename) {
//将base64转换为文件
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), //base64解码JS API(还有一个JS API做base64转码:btoa())
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { //将base64转成文件
type: mime
});
}
// 提交阿里OSS
function submit(imgfile) {
//获取uuid
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//日期格式化
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
"00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
var basePath = new Date().Format('yyyy/MM/dd/');
//paixiu-img/2018/10/24/uuid
client.multipartUpload('图片文件夹名称' + basePath + guid(), imgFile).then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err);
});
}
$('#file').on('change', fileChange);
</script>
</body>
</html>
javascript 使用btoa和atob来进行Base64转码和解码
javascript原生的api本来就支持,Base64,但是由于之前的javascript局限性,导致Base64基本中看不中用。当前html5标准正式化之际,Base64将有较大的转型空间,对于Html5 Api中出现的如FileReader Api, 拖拽上传,甚至是Canvas,Video截图都可以实现。
好了,前言说了一大堆,开发者需要重视:
一.我们来看看,在javascript中如何使用Base64转码
var str = 'javascript';
window.btoa(str)
//转码结果 "amF2YXNjcmlwdA=="
window.atob("amF2YXNjcmlwdA==")
//解码结果 "javascript"
二.对于转码来说,Base64转码的对象只能是字符串,因此来说,对于其他数据还有这一定的局限性,在此特别需要注意的是对Unicode转码。
var str = "China,中国"
window.btoa(str)
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
很明显,这种方式是不行的,那么如何让他支持汉字呢,这就要使用window.encodeURIComponent和window.decodeURIComponent
var str = "China,中国";
window.btoa(window.encodeURIComponent(str))
//"Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ="
window.decodeURIComponent(window.atob('Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ='))
//"China,中国"