base64位字符 上传多张图片保存服务器端



           /**
    * 
    * @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;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值