使用蚂蚁金服ui直接返回的是base64格式的图片
通过post方式进行请求,然后在控制器中以字符串的形式进行接收。
接收之后进行转图片存储处理,只保存路径到数据库中。
base64字节转图片代码:
package com.utils;
import sun.misc.BASE64Decoder;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* Created by Mr Pan
* on 2019/5/20.
*/
public class Base64ToImg {
public static String GenerateImage(String imgStr, String imgFilePath,String rootPath) throws Exception {
if (imgStr == null) // 图像数据为空
return "";
BASE64Decoder decoder = new BASE64Decoder();
// Base64解码,对字节数组字符串进行Base64解码并生成图片
imgStr = imgStr.replaceAll(" ", "+");
System.out.println(imgStr);
byte[] b = decoder.decodeBuffer(imgStr.replace("data:image/jpeg;base64,", ""));
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
String imgName = getRandomFileName()+".jpg";
String dbUrl = "";
// 生成jpeg图片D:\test\attendance\src\main\webapp\assets\images\leave
imgFilePath = "D:\\test\\attendance\\src\\main\\webapp\\assets\\images\\leave\\"+imgName;//新生成的图片
String imgFilePath2 = "D:\\test\\attendance\\target\\assets\\images\\leave\\"+imgName;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
OutputStream out1 = new FileOutputStream(imgFilePath2);
out1.write(b);
out1.flush();
out1.close();
dbUrl = rootPath+"assets/images/leave/"+imgName;
return dbUrl;
}
public static String getRandomFileName() {
SimpleDateFormat simpleDateFormat;
simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
String str = simpleDateFormat.format(date);
Random random = new Random();
int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
return rannum + str;// 当前时间
}
}
getRandomFileName函数是一个产生随机名称的函数,上面代码的函数中将图片输出到了两个地方,如果明确了位置的话,一个就可以了。
有个问题很郁闷的就是前台我想传入一个数组进来,因为上传的图片可能是多个,前台可以用数组传,但是后台没法用数组接收。我这里后台接收是放在map中进行接收的,然后取出来是通过尝试的方法试出来的。。。。
代码如下:
@RequestMapping(value = "/addLeaveItem", method = RequestMethod.POST)
@ResponseBody
public String addLeaveInfo(LeaveInfo leaveInfo,@RequestParam Map params)throws Exception
{
String urlString = new String("");
urlString = Base64ToImg.GenerateImage(params.get("urls[0]").toString(),"D://test","http://localhost:8080/attendance/");
if(params.get("urls[1]") != null){
if(!urlString.equals("")){
System.out.println(urlString);
urlString = urlString + "+" +Base64ToImg.GenerateImage(params.get("urls[1]").toString(),"D://test","http://localhost:8080/attendance/");
}
}
Map<String, Integer> map = new HashMap<String, Integer>();
Integer rows = 0;
if(! "".equals(urlString)){
leaveInfo.setImgs(urlString);
rows = leaveInfoServiceImpl.InsertLeaveInfo(leaveInfo);
}
map.put("data",rows);
// System.out.println(leaveInfo);
return JSON.toJSONString(map);
}
base64传到后台要注意,需要将其中的空格替换为+。这是在传输过程会自动变化的,然后就是内容部分要替换掉,前面的内容,替换为空。