//由于微信端上传是上传至微信服务器返回一个url 所以要定义一个list记录上传成功的文件
var kcidList = []; //记录已成功上传的id
$(".upload-file").change(function() {
var file = $(".upload-file")[0].files[0];
var val = $(this).val();
var arr = val.split('\\');
var fileName = arr[arr.length - 1];
//toLowerCase();//转小写
var fileHz = val.substr(val.indexOf(".")).toLowerCase();
var flieType = "exc.png";
if (fileHz == ".xls") {
flieType = "exc.png";
} else if (fileHz == ".doc" || fileHz == ".docx") {
flieType = "word.png";
} else if (fileHz == ".png" || fileHz == ".jpg" || fileHz == ".jpeg") {
flieType = "pic.png";
//图片特殊处理
uploadFileToService(file,true,flieType);
return;
}
if (file != undefined) {
uploadFileToService(file,false,flieType);
}
});
//将文件上传到服务器
function uploadFileToService(file,isImg,flieType){
if(file.size>2*1024*1024 && isImg){
imageCheck(file.name,flieType);
return;
}
var formdata_file = new FormData();
formdata_file.append("file", file);
$.ajax({
url : "${root}/wechat/action/userCenter/uploadFile.json",
data : formdata_file,
processData : false,
contentType : false,
type : 'POST',
success:function (e) {
var data = $.parseJSON(e);
if(data.success){
kcidList.push(data.message);
console.log(kcidList);
}else{
WechatCommon.layerBomb("上传异常!请重新选择!");
}
}
});
}
function imageCheck(fileName,flieType){
var img = $("#file")[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(img);
reader.onload = function(e){
var base64Img= reader.result;
//--执行resize。
var _ir=ImageResizer({
resizeMode:"auto"
,dataSource:base64Img
,dataSourceType:"base64"
,maxWidth:parseInt(600) //允许的最大宽度
,maxHeight:parseInt(480) //允许的最大高度。
,onTmpImgGenerate:function(img){
}
,success:function(resizeImgBase64,canvas){
var Blob= convertBase64UrlToBlob(resizeImgBase64,'image/png');
var formData = new FormData();
formData.append("files", Blob ,fileName+".png");
$.ajax({
url : "${root}/wechat/uploadFile.json",
data : formData,
processData : false,
contentType : false,
type : 'POST',
success:function (e) {
var data = $.parseJSON(e);
if(data.success){
kcidList.push(data.message);
}else{
WechatCommon.layerBomb("上传异常!请重新选择!");
}
}
});
}
,debug:false
});
};
}
function convertBase64UrlToBlob(dataURI,type){
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type:type });
}
function fileDivList(fileName,flieType){
WechatCommon.layerBomb("文件选择成功!");
$("#approvalFiles").text("报修附件:");
$(".caseDetail-files").show();
$(".showFilesBtn p").show();
$(".hideFiles").append(
'' +
'' +
'' + fileName + '
' +
'');
}
//提交审批按钮
$("#toApproval").click(function() {
var repair_info = {};
repair_info.tel = $("#tel").val();
repair_info.approveInfo = $("#approveInfo").val();//填写的信息文字
var _jsonTxt = JSON.stringify(repair_info);
formdata.append("handleDesc", _jsonTxt);
var kcidStr = kcidList.join(",");
formdata.append("kcidList",kcidStr);
$.ajax({
url : "${root}/wechat/toApproval.json",
data : formdata,
processData : false,
contentType : false,
type : 'POST',
success : function(result) {
var dataJson = $.parseJSON(result);
if (dataJson.success) {
WechatCommon.layerBomb("提交成功");
} else {
WechatCommon.layerBomb(dataJson.message);
}
}
});
});// 提交审批按钮 结束
public List handleFile(HttpServletRequest r, String pathNo) throws IOException {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(r.getSession().getServletContext());
if (multipartResolver.isMultipart(r)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) r;
Iterator iter = multiRequest.getFileNames();
List files = new ArrayList();
while (iter.hasNext()) {
String para = iter.next();
MultipartFile file = multiRequest.getFile(para);
if (file != null) {
if (file.getSize() > fileStore.getMaxFileSize()) {
logger.error("File Upload failed ! File Size can not More then "
+ fileStore.getMaxFileSize() / 1024 + " K");
continue;
}
try {
String myFileName = file.getOriginalFilename();
files.add(writeFile(file.getInputStream(), pathNo, para, file.getSize(), myFileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
return files;
}
return null;
}
private DocumentBean writeFile(InputStream io, String pathNo, String para, long size, String myFileName) {
int index = myFileName.lastIndexOf(".");
String suffix = myFileName.substring(index + 1);
DocumentBean doc = new DocumentBean();
doc.setParameter(para);
doc.setFullname(myFileName);
doc.setSize(size);
doc.setSuffix(suffix);
doc.setFiletype(suffix.toUpperCase());
doc.setName(myFileName.substring(0, index));
try {
doc.setIo(io);
fileStore.saveFile(null, doc, pathNo);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
public DocumentBean saveFile(LoginOpUserInfoVO uInfo,DocumentBean doc,String bizNo) throws Exception{
private HashMap pathMapping;
String folderPath = createFolderForFile(uInfo,DateUtil.getDateStr(new Date())+"/"+pathMapping.get(bizNo)+"/"+System.currentTimeMillis());
Thread.sleep(50);
DocumentBean returndoc = save(uInfo,doc,folderPath);
return returndoc;
}
private DocumentBean save(LoginOpUserInfoVO uInfo,DocumentBean doc,String folderPath) throws Exception{
String pathName = doc.getFullname();
doc.setFolderPath(folderPath);
doc.setNamenPath(folderPath+pathName);
doc.setFolderUrl(folderToUrl(folderPath));
doc.setUrl(folderToUrl(doc.getNamenPath()));
doSaveFile(doc.getIo(),doc.getNamenPath());
return doc;
}
public void doSaveFile(InputStream io,String filePathName) throws IOException {
File file = new File(filePathName);
FileOutputStream out = new FileOutputStream(file);
int i=-1;
byte[] b = new byte[readBufferSize];
while((i=io.read(b))>0){
if(i
/**
* 这是基于html5的前端图片工具,压缩工具。
*/
var ImageResizer=function(opts){
var settings={
resizeMode:"auto"//压缩模式,总共有三种 auto,width,height auto表示自动根据最大的宽度及高度等比压缩,width表示只根据宽度来判断是否需要等比例压缩,height类似。
,dataSource:"" //数据源。数据源是指需要压缩的数据源,有三种类型,image图片元素,base64字符串,canvas对象,还有选择文件时候的file对象。。。
,dataSourceType:"image" //image base64 canvas
,maxWidth:600 //允许的最大宽度
,maxHeight:480 //允许的最大高度。
,onTmpImgGenerate:function(img){} //当中间图片生成时候的执行方法。。这个时候请不要乱修改这图片,否则会打乱压缩后的结果。
,success:function(resizeImgBase64,canvas){
}//压缩成功后图片的base64字符串数据。
,debug:true //是否开启调试模式。
};
var appData={};
$.extend(settings,opts);
var _debug=function(str,styles){
if(settings.debug==true){
if(styles){
console.log(str,styles);
}
else{
console.log(str);
}
}
};
var innerTools={
getBase4FromImgFile:function(file,callBack){
var reader = new FileReader();
reader.onload = function(e) {
var base64Img= e.target.result;
//var $img = $('').attr("src", e.target.result)
//$('#preview').empty().append($img)
if(callBack){
callBack(base64Img);
}
};
reader.readAsDataURL(file);
}
//--处理数据源。。。。将所有数据源都处理成为图片图片对象,方便处理。
,getImgFromDataSource:function(datasource,dataSourceType,callback){
var _me=this;
var img1=new Image();
if(dataSourceType=="img"||dataSourceType=="image"){
img1.src=$(datasource).attr("src");
if(callback){
callback(img1);
}
}else if(dataSourceType=="base64"){
img1.src=datasource;
if(callback){
callback(img1);
}
}else if(dataSourceType=="canvas"){
img1.src = datasource.toDataURL("image/jpeg");
if(callback){
callback(img1);
}
}else if(dataSourceType=="file"){
_me.getBase4FromImgFile(function(base64str){
img1.src=base64str;
if(callback){
callback(img1);
}
});
}
}
//计算图片的需要压缩的尺寸。当然,压缩模式,压缩限制直接从setting里面取出来。
,getResizeSizeFromImg:function(img){
var _img_info={
w:$(img)[0].naturalWidth,
h:$(img)[0].naturalHeight
};
console.log("真实尺寸:");
console.log(_img_info);
var _resize_info={
w:0
,h:0
};
if(_img_info.w<=settings.maxWidth&&_img_info.h<=settings.maxHeight){
return _img_info;
}
if(settings.resizeMode=="auto"){
var _percent_scale=parseFloat(_img_info.w/_img_info.h);
var _size1={
w:0
,h:0
};
var _size_by_mw={
w:settings.maxWidth
,h:parseInt(settings.maxWidth/_percent_scale)
};
var _size_by_mh={
w:parseInt(settings.maxHeight*_percent_scale)
,h:settings.maxHeight
};
if(_size_by_mw.h<=settings.maxHeight){
return _size_by_mw;
}
if(_size_by_mh.w<=settings.maxWidth){
return _size_by_mh;
}
return {
w:settings.maxWidth
,h:settings.maxHeight
};
}
if(settings.resizeMode=="width"){
if(_img_info.w<=settings.maxWidth){
return _img_info;
}
var _size_by_mw={
w:settings.maxWidth
,h:parseInt(settings.maxWidth/_percent_scale)
};
return _size_by_mw;
}
if(settings.resizeMode=="height"){
if(_img_info.h<=settings.maxHeight){
return _img_info;
}
var _size_by_mh={
w:parseInt(settings.maxHeight*_percent_scale)
,h:settings.maxHeight
};
return _size_by_mh;
}
}
//--将相关图片对象画到canvas里面去。
,drawToCanvas:function(img,theW,theH,realW,realH,callback){
var canvas = document.createElement("canvas");
canvas.width=theW;
canvas.height=theH;
var ctx = canvas.getContext('2d');
ctx.drawImage(img,
0,//sourceX,
0,//sourceY,
realW,//sourceWidth,
realH,//sourceHeight,
0,//destX,
0,//destY,
theW,//destWidth,
theH//destHeight
);
//--获取base64字符串及canvas对象传给success函数。
var base64str=canvas.toDataURL("image/png");
if(callback){
callback(base64str,canvas);
}
}
};
//--开始处理。
(function(){
innerTools.getImgFromDataSource(settings.dataSource,settings.dataSourceType,function(_tmp_img){
var __tmpImg=_tmp_img;
settings.onTmpImgGenerate(_tmp_img);
//--计算尺寸。
var _limitSizeInfo=innerTools.getResizeSizeFromImg(__tmpImg);
console.log(_limitSizeInfo);
var _img_info={
w:$(__tmpImg)[0].naturalWidth,
h:$(__tmpImg)[0].naturalHeight
};
innerTools.drawToCanvas(__tmpImg,_limitSizeInfo.w,_limitSizeInfo.h,_img_info.w,_img_info.h,function(base64str,canvas){
settings.success(base64str,canvas);
});
});
})();
var returnObject={
};
return returnObject;
};
html5的压缩工具 对某些浏览器不兼容 导致会压缩失败 但是这针对微信端 微信开发者工具自动的浏览器是100%成功的