工具类
public String localFilePrefix="/huashu-statics";
public String domain="http://www.huashudashi.com";
private String localFilePath="D:/huashu/upload/uploadPath/";
public String base64ToFile(String base64) {
File file = null;
Date date = new Date();
Calendar now = Calendar.getInstance();
String datePath = "/"+now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH) + 1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/";
String filePath=this.localFilePath+datePath;
String fileName = date.getTime()+".png";
File dir=new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.decode(base64);
file=new File(filePath+"/"+fileName);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return this.domain+this.localFilePrefix+datePath+fileName;
}
配置类:
import java.io.File;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler(localFilePrefix + "/**")
.addResourceLocations("file:" + localFilePath + File.separator);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(localFilePrefix + "/**")
.allowedOrigins("*")
.allowedMethods("GET");
}
}