java spring根据外网IP和端口远程读取照片

7 篇文章 0 订阅

最近上传照片的功能需要用到外网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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要获取外网IP地址,可以使用Spring的RestTemplate来发送HTTP请求获取公共IP地址。 首先,你需要创建一个Spring的配置文件,例如application.properties,添加以下配置项: ```properties publicIp.url=http://ifconfig.me/ip ``` 然后,创建一个服务类IpAddressService,使用RestTemplate发送GET请求: ```java @Service public class IpAddressService { @Autowired private RestTemplate restTemplate; @Value("${publicIp.url}") private String publicIpUrl; public String getPublicIpAddress() { return restTemplate.getForObject(publicIpUrl, String.class); } } ``` 在主类中注入该服务类: ```java @SpringBootApplication public class MyApp { @Autowired private IpAddressService ipAddressService; public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } @PostConstruct public void printPublicIpAddress() { String publicIpAddress = ipAddressService.getPublicIpAddress(); System.out.println("Public IP address: " + publicIpAddress); } } ``` 在应用启动后,调用`getPublicIpAddress()`方法即可获取外网IP地址并打印出来。这里使用的是`http://ifconfig.me/ip`这个公共服务来获取IP地址,你也可以使用其他类似的服务。 ### 回答2: 在 Spring 中获取外网 IP 地址可以通过以下步骤实现: 1. 导入相关依赖: 在 Maven 或 Gradle 配置文件中引入 Apache HttpClient 或 OkHttp 等 HTTP 请求库的依赖。 2. 创建一个 HTTP 请求: 使用上述库中的类创建一个 HTTP 请求,指定要请求的外部服务地址。可以选择发送 GET 或 POST 请求,根据具体需求来决定。 3. 发送请求并获取结果: 调用发送请求的方法,并将响应结果保存到一个变量中。 4. 解析响应结果: 对于获取外网 IP 的请求,响应结果通常是一个包含外网 IP 地址的字符串。使用正则表达式或其他方式从结果中提取 IP 地址。 5. 处理和使用 IP 地址: 将获取到的 IP 地址存储到一个变量中,然后可以进行后续的处理或使用。例如,将获取到的 IP 地址保存到数据库或发送到前端页面供用户查看等。 需要注意的是,上述方法获取的是服务端视角下的外网 IP,即应用程序所在服务器的公网 IP。如果需要获取客户端机器的公网 IP,那么由于 HTTP 请求是从客户端发出的,需要在服务器端记录客户端请求的 IP 地址,并从服务器端返回给客户端获取。 ### 回答3: 在Spring中获取外网IP地址有多种方式。下面介绍两种常见的方式: 1. 使用第三方接口:可以通过访问一个提供外网IP的第三方接口来获取。你可以使用Spring提供的`RestTemplate`来发送HTTP请求并解析返回的JSON数据。示例代码如下: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public String getPublicIPAddress() { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://api.ipify.org?format=json", String.class); // 解析返回的JSON获取IP地址 // 代码略 // 返回IP地址 // return ipAddress; } ``` 2. 使用Java的网络工具:可以使用Java的`InetAddress`类来获取本机所在局域网的IP地址,再通过网络工具来获取公网IP地址。示例代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URL; public String getPublicIPAddress() throws IOException { // 获取局域网IP地址 String localIpAddress = InetAddress.getLocalHost().getHostAddress(); // 获取公网IP地址 URL ipUrl = new URL("http://checkip.amazonaws.com"); BufferedReader reader = new BufferedReader(new InputStreamReader(ipUrl.openStream())); String publicIpAddress = reader.readLine(); // 返回公网IP地址 // return publicIpAddress; } ``` 以上两种方式都可以在Spring的服务中使用,根据需求选择其中一种即可。最后,别忘记处理异常和添加必要的异常处理机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值