前端处理JS
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
var width = img.width;
var height = img.height;
var rate = (width<height ? width/height : height/width)/4;
canvas.width = width*rate;
canvas.height = height*rate;
ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) {
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) {
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) {
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
$('.huodong-msg').bind('change',function(event){
var imageUrl = getObjectURL($(this)[0].files[0]);
convertImgToBase64(imageUrl, function(base64Img){
alert(base64Img);
alert(base64Img.split(",")[1]);
});
event.preventDefault();
});
后端处理逻辑
public class AbstractUpload4Base64 {
/**
* 多文件上传
* @param file
* @param request
* @return
*/
public String[] upload(String[] file, HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("activityImg");
Base64 base64 = new Base64();
String[] imageNames = new String[file.length];
if(file != null && file.length!=0){
int index = 0;
for (String base64Str : file) {
byte[] byteArray = base64.decode(base64Str);
for (byte b : byteArray) {
if(b<0)
b+=256;
}
String imageName = this.getImageName();
try {
OutputStream out = new FileOutputStream(path+File.separator+imageName);
out.write(byteArray);
out.close();
} catch (Exception e) {
e.printStackTrace();
return imageNames;
}
imageNames[index] = imageName;
index ++ ;
}
}
return imageNames;
}
/**
* 根据系统规则得到图片名称
*/
public String getImageName(){
return UUID.randomUUID().toString()+".jpg";
}
}