Action
public int test(String myid,String num, String pic) {
//String realPath=ServletActionContext.getServletContext().getRealPath("/upload");
// ServletContext servletContext=request.getSession().getServletContext();
// String realPath=servletContext.getRealPath("/ajaxuploads");
String realPath = request.getServletContext().getRealPath("/ajaxuploads");
File filepath = new File(realPath);
if (!filepath.exists())
filepath.mkdirs();
// 文件保存路径
// String savePath = PICTUREURL + filename1;
if(pic.indexOf("jpeg") != -1) {
//base64字串中有jpeg字串,这是一个4个字的,而我这里是把base64字串的指定位置的字串来作为上传
//文件类型的判断依据,所以在大部分都是三个字的文件类型下就得把jpeg改成jpg了
pic = pic.replaceFirst("jpeg", "jpg");
}
// String upNames = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + buf.toString()+"."+pic.substring(11, 14);
String iconBase64 = pic.substring(22);
String upName =System.currentTimeMillis()+"."+pic.substring(11, 14);
FileOutputStream out;
String s="";
try {
byte[] buffer = new BASE64Decoder().decodeBuffer(iconBase64);
s=realPath+"/"+upName;
System.out.println(s);
// copyFile(pic,realPath+"/"+upName);
out = new FileOutputStream(realPath+"/"+upName);
out.write(buffer);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// copyFile(pic,path);
int n = helloService.adds(myid, num, s);
return n;
}
加密代码
/**
* 加密
*
* @param imgFile
* @return
*/
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
解密代码
public static boolean generateImageFromBase64(String imgStr, String path) {
// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null){ // 图像数据为空
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try{
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i){
if (b[i] < 0){// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
// String imgFilePath = "d://222.jpg";//新生成的图片
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e){
return false;
}
}