一、图片转成base64
public static String getImgStr(String imgFile){
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}
二、保存图片
private static final String BASE_FILE_PATH = "/static/upload";
public static String saveBase64File(String fileBase64, String suffix) {
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
byte[] bytes = Base64.getDecoder().decode(fileBase64);
return saveFile(fileName, bytes);
}
/**
* 保存文件, 按照年月入保存来保存
*/
public static String saveFile(String fileName, byte[] bytes) {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
RequestContextHolder.getRequestAttributes();
//从session里面获取对应的值
String str = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_SESSION);
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
StringBuffer requestURL = request.getRequestURL();
String tempContextUrl = requestURL.delete(requestURL.length() - request.getRequestURI().length(), requestURL.length())
.append(request.getServletContext().getContextPath()).append("/").toString();
ApplicationHome applicationHome = new ApplicationHome(ImageFileUtil.class);
String classPath = applicationHome.getDir().getAbsolutePath();
LocalDateTime localDateTime = LocalDateTime.now();
String absFilePath = BASE_FILE_PATH +
File.separator + localDateTime.getYear() +
File.separator + localDateTime.getMonthValue() +
File.separator + localDateTime.getDayOfMonth() +
File.separator + fileName;
String filePath = classPath + absFilePath;
File file = new File(filePath);
File dir = file.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
fileOutputStream.write(bytes);
fileOutputStream.flush();
return tempContextUrl + absFilePath;
} catch (IOException e) {
log.error("文件保存失败", e);
return null;
}
}
三、访问路径设置
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ApplicationHome applicationHome = new ApplicationHome(getClass());
File file = applicationHome.getDir();
String jarPath = file.getAbsolutePath();
registry.addResourceHandler("/static/upload/**").addResourceLocations(String.format("file:%s/static/upload/", jarPath));
registry.addResourceHandler("/static/app/**").addResourceLocations(String.format("file:%s/static/app/", jarPath));
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/", String.format("file:%s/static/vue/", jarPath));
}
}