zoukankan      html  css  js  c++  java
  • 【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/"); //手机端图片
        }
  • 相关阅读:
    [CQOI2016]手机号码
    花神的数论题
    [AHOI2009]同类分布
    lightoj 1007
    PAT (Advanced Level) 1007. Maximum Subsequence Sum (25) 经典题
    PAT (Top Level)1002. Business DP/背包
    PAT (Advanced level) 1003. Emergency (25) Dijkstra
    HDU 1874 SPFA/Dijkstra/Floyd
    POJ 2823 Sliding Window ST RMQ
    HUST 1103 校赛 邻接表-拓扑排序
  • 原文地址:https://www.cnblogs.com/huashengweilong/p/11217670.html
Copyright © 2011-2022 走看看