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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值