亲测有效
home/include_upload_maxfile.jsp
效果如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();%><%@page import="com.home.base.DBRow"%>
<%@page import="com.home.control.AdminLoggerBean"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>大文件裁剪阿里云oss上传</title><script type="text/javascript" src="js/jquery-1.6.js"></script><style type="text/css"></style></head><body><input type="file" accept="image/*" onchange="getInfo(event)" ><div style='display:none' ><input type="button" id='start_upload' value='开始上传' style='hidden'><input type="button" id='button_start_nouse' value='button_start_nouse' style='hidden'></div><div id='console' ></div><!--https://www.cnblogs.com/2050/p/3913184.html--><!-- 阿里云上传 开始 --> <link rel="stylesheet" type="text/css" href="oss-h5-upload/style.css"/><script type="text/javascript" src="oss-h5-upload/lib/crypto1/crypto/crypto.js"></script><script type="text/javascript" src="oss-h5-upload/lib/crypto1/hmac/hmac.js"></script><script type="text/javascript" src="oss-h5-upload/lib/crypto1/sha1/sha1.js"></script><script type="text/javascript" src="oss-h5-upload/lib/base64.js"></script><script type="text/javascript" src="oss-h5-upload/lib/plupload-2.1.2/js/plupload.full.min.js"></script><script type="text/javascript" >accessid= '12323';accesskey= '12323asdfasdfas';host = 'http://static.12345.com';g_dirname = ''g_object_name = ''g_object_name_type = ''now = timestamp = Date.parse(new Date()) / 1000; var policyText = {"expiration": "2031-01-01T12:00:00.000Z", //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了"conditions": [["content-length-range", 0, 1048576000] // 设置上传文件的大小限制]};var policyBase64 = Base64.encode(JSON.stringify(policyText))message = policyBase64var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;var signature = Crypto.util.bytesToBase64(bytes);function getNowFormatDate() {var date = new Date();var seperator1 = "-";var year = date.getFullYear();var month = date.getMonth() + 1;var strDate = date.getDate();if (month >= 1 && month <= 9) {month = "0" + month;}if (strDate >= 0 && strDate <= 9) {strDate = "0" + strDate;}var currentdate = year + seperator1 + month + seperator1 + strDate;return currentdate;}function get_dirname(){dir = document.getElementById("dirname").value;if (dir != '' && dir.indexOf('/') != dir.length - 1){dir = dir + '/'}//alert(dir)g_dirname = dir}function random_string(len) {len = len || 32;var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = chars.length;var pwd = '';for (i = 0; i < len; i++) {pwd += chars.charAt(Math.floor(Math.random() * maxPos));}return pwd;}function get_suffix(filename) {pos = filename.lastIndexOf('.')suffix = ''if (pos != -1) {suffix = filename.substring(pos)}return suffix;}function set_upload(up,filename, ret){var suffix = get_suffix(filename)var first='static/';g_object_name = ''+first+getNowFormatDate()+'/' + random_string(10) + suffixvar new_multipart_params = {'key' : g_object_name,'policy': policyBase64,'OSSAccessKeyId': accessid, 'success_action_status' : '200', //让服务端返回200,不然,默认会返回204'signature': signature};new_multipart_params;up.setOption({'url': host,'multipart_params': new_multipart_params});}//实例化一个plupload上传对象var uploader = new plupload.Uploader({'url': host,browse_button : 'button_start_nouse', //触发文件选择对话框的按钮,为那个元素idflash_swf_url : 'oss-h5-upload/lib/plupload-2.1.2/js/Moxie.swf',silverlight_xap_url : 'oss-h5-upload/lib/plupload-2.1.2/js/Moxie.xap',max_file_size: '2mb'}); //绑定各种事件,并在事件监听函数中做你想做的事uploader.bind('FilesAdded',function(uploader,files){console.log(":FilesAdded"); //每个事件监听函数都会传入一些很有用的参数,//我们可以利用这些参数提供的信息来做比如更新UI,提示上传进度等操作});uploader.bind('BeforeUpload',function(uploader,files){console.log("BeforeUpload"); set_upload(uploader, files.name, true);var tmp=$("#console").html();tmp=tmp+"<p style='text-align:center'><span style='color:black;font-weight: bold;'>0%</span></p>";$("#console").html(tmp);});uploader.bind('UploadProgress',function(uploader,file){//每个事件监听函数都会传入一些很有用的参数,var str=file.percent;console.log("UploadProgress-"+str); //我们可以利用这些参数提供的信息来做比如更新UI,提示上传进度等操作$("#console").find('span').text("上传"+str+"%"); });uploader.bind('FileUploaded',function(up, file, info){console.log("得到文件:FileUploaded"); if (info.status == 200){var url=host+"/"+g_object_name;$("#console").html("<img width=100px src='" + url + "' />");}else{alert('error');}//每个事件监听函数都会传入一些很有用的参数,//我们可以利用这些参数提供的信息来做比如更新UI,提示上传进度等操作});//最后给"开始上传"按钮注册事件document.getElementById('start_upload').onclick = function(){uploader.start(); //调用实例对象的start()方法开始上传文件,当然你也可以在其他地方调用该方法}//在实例对象上调用init()方法进行初始化uploader.init();function getInfo(event){let reader = new FileReader();//这里把一个文件用base64编码reader.readAsDataURL(event.target.files[0]); reader.onload = function(e){let newImg = new Image();//获取编码后的值,也可以用this.result获取newImg.src = e.target.result;newImg.onload = function () {/* 获取 this.height tthis.width*/var dataURL = compress(newImg,this.width,this.height,0.8);/*为了兼容ios 需要 dataURL-> blob -> file */var blob = dataURLtoBlob(dataURL); // dataURL-> blob var tmpName="tmpName.jpg";//强制.jpgvar file = blobToFile(blob, tmpName); // blob -> fileconsole.log("得到文件:"+file); console.log("压缩后大小:"+file.size/1024); $("#console").html("<img width=100px src='" + dataURL + "' />");uploader.addFile(file);$('#start_upload').click();}}} function compress(img, width, height, ratio) { // img可以是dataURL或者图片url/* 如果宽度大于 750 图片太大 等比压缩 */if(width > 750){var ratio = width/height;width = 750;height = 750/ratio;} var canvas, ctx, img64;canvas = document.createElement('canvas');canvas.width = width;canvas.height = height;ctx = canvas.getContext("2d");ctx.drawImage(img, 0, 0, width, height);/* canvas.toDataURL(mimeType(图片的类型), qualityArgument(图片质量)) */img64 = canvas.toDataURL("image/jpeg", ratio);return img64; // 压缩后的base64串}//将base64转换为blobfunction dataURLtoBlob (dataurl) { var arr = dataurl.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 Blob([u8arr], { type: mime });}//将blob转换为filefunction blobToFile(theBlob, fileName){theBlob.lastModifiedDate = new Date();theBlob.name = fileName;return theBlob;}</script></body>
</html>