前端传来文件/流/base64字符串.
后端需要对其进行保存
(1)保存需要一个服务器本地磁盘的路径,
本地磁盘的话需要动态的去项目的同级目录去新建一个文件夹来保存
目的是保存
public static String getSavePath() throws FileNotFoundException {
// 项目路径
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists())
path = new File("");
// 绝对路径=项目路径+自定义路径
File upload = new File(path.getAbsolutePath(), "static/pic/");
if (!upload.exists())
upload.mkdirs();
System.err.println("path1::" + upload.getAbsolutePath());//path1是正常的,和src同级
// 绝对路径=项目路径+打包的
// String path2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
// System.err.println("path2"+path2);//path2的中文是乱码,/target/classes/
return upload.getAbsolutePath();
}
后面再拼写下.jpg就好了
(2)也需要一个服务器url路径
也要求要动态地获取
目的是给前端访问
@Component
public class ServerAddressAndPort implements ApplicationListener<WebServerInitializedEvent> {
private int serverPort;
public String getUrl() throws UnknownHostException {
InetAddress address = null;
address = InetAddress.getLocalHost();
return "http://" + address.getHostAddress() + ":" + this.serverPort;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
this.serverPort = event.getWebServer().getPort();
}
}
同样,后面拼写下.jpg就好了
springmvc配置静态访问资源
spring:
mvc:
static-path-pattern: /**
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/static/,classpath:/static/,classpath:/public/,file:${web.upload-path},file:./static/pic/
file:./static/pic/ 代表项目的同级目录,这种是相对路径的写法
file:xxx/xxx/xxx,这种是绝对路径的写法
这边的要点:static-locations覆盖默认的静态资源路径的配置信息,因此要重新补上去原有配置的静态路径才可以