【Java】【34】网络资源(图片)下载到本地

本文介绍了一种将URL地址中的图片下载并存储到自己服务器的方法,通过ImgUtil类的downloadImg方法实现图片的下载和保存,同时配置了MvcConfig使http访问能正确指向本地文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:有的时候我们要把url地址的图片存到自己的服务器上,比如微信用户信息的头像

正文:

ImgUtil.class(下载图片的公共方法)

private static String downloadImg(String url, String fileName) throws IOException {
    logger.info(String.format("downloadImg url:%s,fileName:%s", url, fileName));
    
    if (StringUtils.isEmpty(url)) { 
        return Config.DEFAULT_AVATAR; //如果地址为空返回默认头像
    }
    
    String savePath = "head/";
    String filePath = Config.MEDIA_FILE + savePath + fileName; //C:/production/studio/head/1.jpg
    
    URL imageUrl = new URL(url);              
    URLConnection con = imageUrl.openConnection(); //打开连接   
    InputStream is = con.getInputStream(); //输入流  
    byte[] bs = new byte[8192]; //8K的数据缓冲           
    int len; //读取到的数据长度   
    File file = new File(filePath);  
    OutputStream os = new FileOutputStream(file); //输出的文件流
    //开始读取  
    while ((len = is.read(bs)) != -1) {  
        os.write(bs, 0, len);  
    }  
    //完毕,关闭所有链接  
    os.close();  
    is.close();  
    String realUrl = Config.REAL_MEDIA_DOMAIN + savePath + fileName; //http://test.com/media/head/1.jpg

    logger.info("downloadImg success, realUrl=" + realUrl);
    
    return realUrl;
}

MvcConfig.class(使http://test.com/media可以指向到file:C:/production/studio)

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/");  //等价于原mvc-config.xml中 <mvc:resources mapping="/**" location="/"/>
        registry.addResourceHandler("/media/**").addResourceLocations("file:C:/production/studio/"); //手机端图片
    }

 

转载于:https://www.cnblogs.com/huashengweilong/p/11217670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值