base64格式上传图片后台写入

 

前台

var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){//回调

后台

try {
if (imgurl == null){ //图像数据为空
response.getWriter().write("fail");
} else{
File dir=new File("/nfs/optiontemp/"+imgdir);//文件夹路径
if(!dir.isDirectory()&&!dir.exists()){//是否存在不存在创建
dir.mkdir();
}
String strtype=imgtype.substring(6);
Date date=new Date();
String name=imgname+"_"+date.getTime();
File file=new File(dir+"/"+name+"."+strtype); //文件
if(!file.exists()){
file.createNewFile();//创建文件
}
//Base64解码
BASE64Decoder decoder = new BASE64Decoder();
//去掉base64的头部结构:如;data:image/png;base64注意有些还需要去空白此处没写
byte[] b = decoder.decodeBuffer(imgurl.replace("data:"+imgtype+";base64,",""));
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(file); //写入文件
out.write(b);
out.flush();
out.close();
response.getWriter().write("success");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

posted @ 2018-12-06 16:13  萝卜爱吃肉  阅读(327)  评论(0编辑  收藏  举报