B服务器上nginx配置
location /fz/ {
proxy_pass http://ipA:8036/;
proxy_set_header host $host;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
}
#把/file/file/ 前缀改写为 /upload/,其余路径原样转发
location /file/file/ {
proxy_pass http://ipA:8036/upload/file/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
请求地址图片
http://ipB:8030/file/file/upload/TestImg/20261203/17D4408E-1227-4A93-B2BB-3AF7C8767167.jpg
实际转向地址
http://ipA:8036/upload/file/upload/TestImg/20261203/17D4408E-1227-4A93-B2BB-3AF7C8767167.jpg
http://ipA:8036/upload/file/upload/TestImg/20261203/17D4408E-1227-4A93-B2BB-3AF7C8767167.jpg
upload = currentDir (/app) = 真实位置/home/sunplus
-
请求:
/file/file/upload/TestImg/20261203/xxx.jpg -
切掉
/file/file/→ 剩余upload/TestImg/20261203/xxx.jpg -
拼到
/upload/file/→/upload/file/upload/TestImg/20261203/xxx.jpg
java代码
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/file/**").addResourceLocations("file:D:/");
String currentDir = System.getProperty("user.dir");
currentDir = currentDir.replaceAll("\\\\", "/")+"/";
System.out.println(currentDir);
log.info("=========================currentDir:"+currentDir);
registry.addResourceHandler( "/upload/**", "/uploads/**")
.addResourceLocations("file:"+currentDir);
}
}
currentDir=/app
挂载配置为 -v /home/sunplus:/app \
文件上传地址为/app空间内 /file/upload/TestImg/
实际宿主机位置为/home/sunplus/file/upload/TestImg/
registry.addResourceHandler("/upload/**", "/uploads/**")
这意味着 Spring MVC 只会拦截以 /upload/ 或 /uploads/ 开头的请求,并去你配置的目录(即 System.getProperty("user.dir")) /app==>/home/sunplus/ 下查找文件。