将图片保存到本地,然后将路径放到数据库中
一、调用方法
//传入参数 图片编码,前缀,然后获取到相对路径,将pic存入数据库
String pic1 =uploadLocal(bestImage,"pic1");
二、实现保存到本地方法
//此方法是将图片下载到本地,传入的参数plateImage 是图片得base64编码,qianzhui 是 图片得一个前缀
private String uploadLocal(String plateImage,String qianzhui ) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String datestr = sdf.format(new Date());
// 本地路径与时间拼接
String FilePath = "/ruoyi/"+datestr;
// 将本地路径放入到file文件中,检查如果没有此路径创建新得目录
// 创建一个File对象来表示上述路径。如果该路径不存在,则调用mkdirs()方法创建所有必需的父目录。
File file = new File(FilePath);
if (!file.exists()) {
// 创建文件根目录
file.mkdirs();
}
String ImageDataUrl="";
String dbpath = null;
if(plateImage!=null && !plateImage.equals("") && plateImage.length()>0) {
//获取图片编码base64
// byte[] filebyte = Base64Utils.decode(plateImage.getBytes());
byte[] filebyte = Base64.getDecoder().decode(plateImage); // 正确解码Base64字符串
// byte[] filebyte = plateImage.getBytes();
System.out.println(filebyte);
//拼接图片名字
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String pic_time = sdf1.format(date);
String orgName ="/"+qianzhui+pic_time+"_image.jpg";
//添加路径
String savePath =FilePath+ orgName;
File savefile = new File(savePath);
FileOutputStream fos = new FileOutputStream(savefile);
fos.write(filebyte);
// 返回文件的绝对路径
ImageDataUrl = savefile.getPath();
System.out.println(ImageDataUrl);
//拼接相对路径
dbpath = "/ruoyi/"+datestr + orgName;
}
return dbpath;
}