最近上传照片的功能需要用到外网IP
和端口,但是查了一圈没找到,最后在stackoverflow
发现了一个方法,供参考。
获取公网IP
的方法,通过使用亚马逊的网站可以获取公网IP
。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class IpChecker {
public static String getIp() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
获取端口的方法:
import org.springframework.core.env.Environment;
@Autowired
Environment environment;
String port = environment.getProperty("server.port")
这里我们上传照片主要是将照片保存在服务器上,然后将公网IP+链接+相对地址
保存在数据库中,前端需要照片时,通过读取数据库照片相关链接即可进行读取。之前想过将照片转成base64
字符串或者byte数组进行存储,但是网上并不建议这么做,因为照片存储空间较大。因此还是考虑的将照片放在某个文件夹里,通过公网IP+链接+相对地址
进行访问。下面是spring
的一些配置。
当我们访问照片时,我们存储在某个文件加下面的照片可以通过file://+某个文件夹+照片名
来访问。举个例子:
我们可以通过file://myfile/haha.jpg
可以访问文件夹为myfile
下面图片名为haha.jpg
的图片。在Spring
进行addResourceHandler("/img/**")
配置,我们可以通过访问Spring服务器地址+/img/+haha.jpg
即可访问该网址对应的服务器的文件夹(myfile
)下面的图片haha.jpg
。
@Configuration
class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new String2LocalDateTimeConverter());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("file://"+System.getProperty("user.home")+"/myfile/");
super.addResourceHandlers(registry);
}
}
通过将照片上传到服务器的img
文件夹下面,将链接设置为Spring的公网IP端口+/img/+图片名
,即可通过链接访问。
附上传照片的代码:
public void uploadPhoto(String id, MultipartFile file, HttpServletRequest request){
Logger log = LoggerFactory.getLogger(this.getClass());
if(eMapper.getE(id) == null){
throw new ASException(NOT_EXISTS.getCode(),
String.format("上传照片失败", id),
NOT_EXISTS.getMsg());
}
String pathRoot = null;
try {
pathRoot = "http://" + IpChecker.getIp() //服务器地址
+ ":" + environment.getProperty("server.port"); //端口号
} catch (Exception e) {
e.printStackTrace();
}
String relativePath="";
if (!file.isEmpty()) {
//生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String contentType = file.getContentType();
//获得文件后缀名称
String imageName = contentType.substring(contentType.indexOf("/") + 1);
String imageFullName = uuid + "." + imageName;
relativePath = "/myfile/" + imageFullName;
//照片实际在服务器上存储地址
String totalPath = System.getProperty("user.home")+relativePath;
File dest = new File(totalPath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
throw new ASException(FAILED_TO_UPLOAD.getCode(), "上传照片失败", FAILED_TO_UPLOAD.getMsg());
}
PDO pDO = PDO.builder()
.eId(equipmentId)
// 我们访问的照片地址
.pLink(pathRoot + "/img/"+imageFullName)
.createTime(LocalDateTime.now())
.build();
ePMapper.addPLink(pDO);
}
request.setAttribute("pLink", pathRoot + "/img/"+imageFullName);
}
参考文献:
Getting the ‘external’ IP address in Java
Serving Static resources from file system | Spring Boot Web