一、addResourceHandlers:预览图片和pdf,其他文件不支持
图片或者视频存放在专门的服务器上面(Windows服务器),假设存储路径为C:uploaddatapicture 该路径下面存储的是所有需预览的图片。
1、 模拟创建实体类表
// 检测数据
public Class CheckData {
// 检测数据名称
private String name;
// 文件路径(c:uploaddatapicture1.png)
private String filePath;
}
2、 添加配置类
@Configuration
public class FileConfig implements WebMvcConfigurer {
@Value("${file.config.diskPath}")
// 文件本地路径 c:
private String diskPath;
@Value("${file.config.pathPattern}")
// /file
private static final String NETWORK_CARD = "eth0";
private static final String NETWORK_CARD_BAND = "bond0";
static String OS_NAME = System.getProperty("os.name").toLowerCase();
private static Thread startPreviewServer;
public static String startPreviewServer(String location) throws UnknownHostException {
if (startPreviewServer == null ) {
startPreviewServer = new Thread() {
@SneakyThrows
public void run() {
publishService();
}
};
startPreviewServer.start();
}
String localPath = StringUtils.replace(location, ServletUtils.getOSName(), "");
if (OS_NAME.contains("windows")) {
return "http://" + getHostInfo() + ":" + PreviewPort + FileDir + localPath;
} else{
return "http://" + "139.159.233.243" + ":" + PreviewPort + FileDir + localPath;
}
}
private static void publishService() throws UnknownHostException {
String hostIp = getHostInfo();
Server server = new Server(new InetSocketAddress(hostIp, Integer.valueOf(PreviewPort)));
// 配置要监控的本地目录和要访问的http映射url
WebAppContext webContext = new WebAppContext(FilePreviewDir(ServletUtils.getOSName()), FileDir);
server.setHandler(webContext);
System.out.println("preview server is starting...");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
// 监控的本地路径
public static String FilePreviewDir(String location) {
// XXX 可以修改使用配置文件获取本地监控路径,方便扩展
return location;
}
private static String getHostInfo() throws UnknownHostException {
// XXX 可以修改使用配置文件获取host地址,方便扩展
if (OS_NAME.contains("windows")) {
return InetAddress.getLocalHost().getHostAddress();
} else{
return getLocalIP();
}
}
public static String getLocalIP() {
String ip = "";
try {
Enumeration e1 = (Enumeration)NetworkInterface.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = e1.nextElement();
//单网卡或者绑定双网卡
if ((NETWORK_CARD.equals(ni.getName()))
|| (NETWORK_CARD_BAND.equals(ni.getName()))) {
Enumeration e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = e2.nextElement();
if (ia instanceof Inet6Address)
{
continue;
}
ip = ia.getHostAddress();
}
break;
}
else {
continue;
}
}
}
catch (SocketException e) {
logger.error("IP出现异常!异常信息:" + e.getMessage());
}
return ip;
}
}
上面直接运行Application即可启动web服务,然后访问:http://192.168.2.32:8091/preview/1534436235735465986/photo/10-12.jpg,
地址,便可进入日志的监控目录:
【注意】:
1.windows上通过InetAddress.getLocalHost().getHostAddress()获取的是局域网的ip(192.168.2.32)。
linux上通过InetAddress.getLocalHost().getHostAddress()获取的是127.0.0.1。
2.linux需要单独获取到ip(192.168.0.78)的方法,再将其映射到公网IP(139.159.233.***)上。



