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

前言:有的时候我们要把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