@RequestMapping("/saveToImgByStr")
@ResponseBody
public Map<String,Object> saveToImgByStr(@RequestBody Map<String,Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
UserBean user = this.detectUserBean(request).getUserBean();
JSONObject jsonObj =new JSONObject();
Map<String,Object>res=new HashMap<>();
//Integer sqId =map.get("sqId")!=null?Integer.parseInt(String.valueOf(map.get("sqId"))):0;
String imgByte=map.get("baseStr")!=null?(String) map.get("baseStr"):"";
if(org.springframework.util.StringUtils.isEmpty(imgByte)){
logger.error("saveToImgByStr->ERROR baseStr:"+imgByte);
throw new Exception();
}
/* response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");*/
imgByte = imgByte.substring(imgByte.indexOf(",") + 1);
Double byteNum = base64FileSize(imgByte);
BigDecimal fileByte = new BigDecimal(byteNum);
if(!bytesToMb(fileByte)){
jsonObj.put("msg","文件大小不得超过5M");
jsonObj.put("flag",false);
res.put("status",false);
return res;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] imageByte = null;
try{
imageByte = decoder.decodeBuffer(imgByte);
for (int i = 0; i < imageByte.length; ++i) {
if (imageByte[i] < 0) {// 调整异常数据
imageByte[i] += 256;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("saveToImgByStr->decoder.decodeBuffer ERROR");
}
if (imageByte.length>0) {
try {
//获取文件上传的真实路径
//String uploadPath = request.getSession().getServletContext().getRealPath("/");
//保存文件的路径
String uploadDir = "upload"+ File.separator+user.getDefaultArea().getAreaCode()+File.separator+"reply"+File.separator;
File destfile = new File(baseImgPath + uploadDir);
if (!destfile.exists()) {
destfile.mkdirs();
}
//文件新名称
String fileNameNew = UUID.randomUUID().toString() + ".png";
File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
// 将字符串转换成二进制,用于显示图片
// 将上面生成的图片格式字符串 imgStr,还原成图片显示
InputStream in = new ByteArrayInputStream(imageByte);
FileOutputStream fos = new FileOutputStream(f);
// BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buf = new byte[1024];
int length;
length = in.read(buf, 0, buf.length);
while (length != -1) {
fos.write(buf,0,length);
length = in.read(buf);
}
fos.flush();
fos.close();
in.close();
//图片上传完成 插入图片
//int fileId = yqjkService.insertSqsbRelavationFile(sqId, uploadDir+fileNameNew);
jsonObj.put("flag",true);
jsonObj.put("url",viewImgFileRootPath+ uploadDir+fileNameNew);
jsonObj.put("uploadDir",uploadDir+fileNameNew);
res.put("status",true);
res.put("data",jsonObj);
} catch (Exception e) {
e.printStackTrace();
res.put("status",false);
logger.error("上传图片 ERROR->saveToImgByStr");
}
}
return res;
}
/**
* 精确计算base64字符串文件大小(单位:B)
* @param base64String
* @return
*/
public static double base64FileSize(String base64String) {
/**检测是否含有base64,文件头)*/
if (base64String.lastIndexOf(",") > 0) {
base64String = base64String.substring(base64String.lastIndexOf(",")+1);
}
/** 获取base64字符串长度(不含data:audio/wav;base64,文件头) */
int size0 = base64String.length();
/** 获取字符串的尾巴的最后10个字符,用于判断尾巴是否有等号,正常生成的base64文件'等号'不会超过4个 */
String tail = base64String.substring(size0 - 10);
/** 找到等号,把等号也去掉,(等号其实是空的意思,不能算在文件大小里面) */
int equalIndex = tail.indexOf("=");
if (equalIndex > 0) {
size0 = size0 - (10 - equalIndex);
}
/** 计算后得到的文件流大小,单位为字节 */
return size0 - ((double) size0 / 8) * 2;
}
/**
* byte(字节)根据长度转成kb(千字节)和mb(兆字节)
*
* @return
*/
public static Boolean bytesToMb(BigDecimal filesize) {
BigDecimal megabyte = new BigDecimal(1024 * 1024);
float returnValue = filesize.divide(megabyte, 1, BigDecimal.ROUND_DOWN).floatValue();
BigDecimal fileSize = new BigDecimal(returnValue);
BigDecimal needFile = new BigDecimal("5");
if(fileSize.compareTo(needFile)>0){
return false;
}else{
return true;
}
}
前端上传base64图片string到文件服务器