/**
*
* @param strimg base64位字符 转图片保存服务器端
* @param request
* @return 返回图片服务器地址
*/
public String uploadImg(String strimg ,HttpServletRequest request){
String uploadUrl="";
if(strimg!=null&&!"".equals(strimg)){
String[] str =strimg.split(";");
Uploader up =new Uploader(request);
boolean imgtype=up.checkFileType("."+str[0].split("/")[1]);
if(imgtype==false){
return "{\"status\":\""+ imgtype +"\", \"message\": \"上传图片类型错误,请选择正确图片类型!\",\"url\":
\""+11 +"\"}";
}
uploadUrl = up.uploadBase64(str[1].split(",")[1]);
}
return uploadUrl;
}
public class Uploader {
// 保存路径
private String savePath = "upload";
// 输出文件地址
private String url = "";
// 上传文件名
private String fileName = "";
/**
* 根据字符串创建本地目录 并按照日期建立子目录返回
* @param path
* @return
*/
private String getFolderBase(String path) {
String realPath =this.request.getSession().getServletContext()
.getRealPath(path);
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
String creatpath = realPath+"/" + formater.format(new Date());
File dir = new File(creatpath);
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
this.state = this.errorInfo.get("DIR");
return "";
}
}
return creatpath;
}
/**
* 依据原始文件名生成新文件名
* @return
*/
private String getName(String fileName) {
Random random = new Random();
return this.fileName = "" + random.nextInt(10000)
+ System.currentTimeMillis() + this.getFileExt(fileName);
}
/**
* 接受并保存以base64格式上传的文件
* @param fieldName
*/
public String uploadBase64(String base64Data){
String savePath = this.getFolderBase((this.savePath));
//String base64Data = this.request.getParameter(fieldName);
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
this.fileName = this.getName("test.png");
String creatpath = this.savePath+"/" + formater.format(new Date())+"/"+this.fileName;
this.url = savePath + "/" + this.fileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
File outFile = new File(this.url);
OutputStream ro = new FileOutputStream(outFile);
byte[] b = decoder.decodeBuffer(base64Data);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
ro.write(b);
ro.flush();
ro.close();
this.state=this.errorInfo.get("SUCCESS");
} catch (Exception e) {
this.state = this.errorInfo.get("IO");
}
return creatpath;
}
}